之前写了一下prepareForSegue方法的使用,那时候只是大概知道怎么回事。这次来阐明一些更细节的数据传递的问题。
我门要从AllListsViewController跳转到ChecklistViewController,并向其传递数据。首先我们先在ChecklistViewController中定义接收数据的变量。这里用感叹号的原因是:nil is normally not an allowed value for variables in Swift but by using the ! you override that. 即viewDidLoad()被执行前,允许checklist为nil。
var checklist: Checklist!
这里的Checklist!是我们在另一个文件Checklist.swift中定义的类,他具有name的属性。
import UIKit
class Checklist: NSObject {
var name = ""
init(name: String)
{
self.name = name
// Because both the parameter and the instance variable are called name, you use self.name to refer to the instance variable. self.name=(var name = "")
super.init()
}
}
然后,在AllListsViewController中,我们使用prepareForSegue方法向ChecklistViewController传递数据
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//Tells the delegate that the specified row is now selected.
let checklist = lists[indexPath.row]//
performSegueWithIdentifier("ShowChecklist", sender: checklist)
// 这个函数相当于在初始化segue,但此时segue还没有被传送给ChecklistViewController
// 由于performSegueWithIdentifier是在tableView(didSelectRowAtIndexPath)函数里面调用的。所以,点击一行的操作执行之后,performSegueWithIdentifier将被调用
// 从 Checklists Scene 跳转到 Name of the Checklist
// Segue(Checklists Scene 到 Name of the Checklist的Segue名字叫ShowChecklist)
// 点击一行的时候,这个method将被调用
// The object that you want to use to initiate the segue.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Notifies the view controller that a segue is about to be performed.
if segue.identifier == "ShowChecklist"{
let controller = segue.destinationViewController as! ChecklistViewController
controller.checklist = sender as! Checklist
// By writing “sender as! Checklist”, you tell Swift that it can safely treat sender as a Checklist object.
}
}
来解释一下这两个方法的内容。第一个是segue的初始化,并定义sender是一个常量checklist。注意,这里的checklist = lists[indexPath.row],说明checklist是一个Checklist类的常量。当点击一行的时候将被调用。第二个是正式的prepareForSegue。先判断segue.identifier是不是我们预先在故事版定义的值。然后令controller为destinationViewController,也就是我们要跳转到的ChecklistViewController。注意,这里的as告诉编译器,segue指向的是ChecklistViewController类的变量。然后,我们通过controller.checklist = sender as! Checklist,把sender的内容传递给ChecklistViewController。