Uitableview 从所选行获取导航栏标题

Uitableview 从所选行获取导航栏标题,uitableview,swift,title,navigationbar,Uitableview,Swift,Title,Navigationbar,我创建了一个表视图,用户可以通过单击导航栏中的“添加”按钮来添加行。当用户选择一行时,应用程序将显示另一个表视图。我想将导航栏的标题设置为所选行的名称 如果在第二个表视图中将名称传递给标签,我知道如何设置导航栏的标题 title = self.restaurant.name 但我还没有弄清楚如何在不创建额外标签的情况下将其传递到导航栏 这其实很容易。您只需实现prepareForSegue并使用sender创建UITableViewCell的实例。从那里,您可以轻松获得该单元格的标题,并使用

我创建了一个表视图,用户可以通过单击导航栏中的“添加”按钮来添加行。当用户选择一行时,应用程序将显示另一个表视图。我想将导航栏的标题设置为所选行的名称

如果在第二个表视图中将名称传递给标签,我知道如何设置导航栏的标题

title = self.restaurant.name 

但我还没有弄清楚如何在不创建额外标签的情况下将其传递到导航栏

这其实很容易。您只需实现
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
    }
}

其实很简单。您只需实现
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
    }
}