我创建了一个表格视图,用户可以通过点击"添加"来添加行。导航栏中的按钮。当用户选择一行时,应用程序会显示另一个表视图。我想将导航栏的标题设置为所选行的名称。
如果我在第二个表格视图中将名称传递给标签,我知道如何设置导航栏的标题。
title = self.restaurant.name
但我还没弄明白如何在不创建额外标签的情况下将其传递到导航栏。
答案 0 :(得分:5)
实际上这很容易。您所要做的就是实现prepareForSegue
并使用sender
来创建UITableViewCell的实例。从那里您可以轻松获取该单元格的标题,并使用segue.destinationViewController
您可以设置后续视图控制器的导航栏标题。
import Foundation
import UIKit
class TableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellID", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = "Cell at row \(indexPath.row)"
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destinationVC = segue.destinationViewController as UIViewController
let cell = sender as UITableViewCell
destinationVC.navigationItem.title = cell.textLabel?.text
}
}