我正在执行从 TableViewController(嵌入在 NavigationController 中)到另一个 TableViewController 的 segue(通过情节提要)。即选择一个单元格并呈现另一个TableView,我想在其上显示所选单元格的文本作为下一个视图标题。
我正在实现这一点,但不是 100% 正确。在第一次初始选择单元格时,未设置 navigationItem 标题。只有当我向后导航然后再次通过同一个单元格时,才会设置标题。
第一个片段是我的第一个 viewController,我正在选择一个单元格,在该单元格上我使用所选单元格标题设置 destinationViewControllers 变量。
var valueToPass:String?
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You selected cell #\(indexPath.row)!")
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!;
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!;
valueToPass = currentCell.textLabel!.text
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "tripSegue") {
// initialize new view controller and cast it as your view controller
let viewController = segue.destinationViewController as! TripTableViewController
// setting the view controllers property that will store the passed value
viewController.passedValue = valueToPass
}
}
第二个片段来自destinationViewController 设置navigationItem 标题。
var passedValue: String?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = passedValue
}