0

我正在执行从 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
}
4

1 回答 1

1

这是因为之前prepareForSegue调用 didSelectRowAtIndexPath。所以第一次选择一行时,valueToPass为 nil。在仍然为 nilprepareForSegue时调用它并且您传递它,然后在您传递它之后,称为设置为所需的值,这是您下次选择行时传递的值。valueToPassdidSelectRowAtIndexPathvalueToPass

您需要在prepareForSegue.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

if (segue.identifier == "tripSegue") {
       // Get Cell Label
       let indexPath = self.tableView.indexPathForSelectedRow!;
       let currentCell = self.tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell!;
       // 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 = currentCell.textLabel!.text

    }
}
于 2015-09-25T02:39:40.773 回答