尝试将选定的 tableview 单元格值传递给 swift 中的 NavigationBar 标题

Trying to Pass a selected tableview cell value to a NavigationBar Title in swift

请原谅新手的问题,我一直在尝试一切,但无法让它发挥作用:(

我在表格视图中有一个列表,理想情况下,当一个单元格(行)被选中时,它会将所选单元格文本显示为导航栏的标题。

这是我认为应该将所选值传递给下一个 segue 的调用

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    
    let selectedTopic = Topics[indexPath.row]
    
    let Sentences = SentencesVC()
    Sentences.TopicPassed = selectedTopic.heading
    
    self.performSegueWithIdentifier("gotoSentences", sender: tableView)
    let pathSelect = TopicTableView.indexPathForSelectedRow()
    pathSelect
}

另一个ViewController的代码:

var TopicPassed:String!

@IBOutlet weak var NavBar: UINavigationBar!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    self.navigationItem.title = TopicPassed
    
}

任何帮助将不胜感激,因为它让我发疯,我不确定我尝试了多少次不同的解决方案都无济于事。

提前致谢

像这样更改您的 segue:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if (segue.identifier == "gotoSentences") {
        var otherView = segue.destinationViewController as OtherViewController;

        var index = mainTableView.indexPathForSelectedRow()

        otherView.title = Topics[index.row]
    }

}

当您使用故事板和 segues 时,请将此函数添加到您的视图控制器的代码中:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if segue.identifier == "gotoSentences" {
        let selectedTopic = Topics[tableView.indexPathForSelectedRow().row]
        let sentences = segue.destinationViewController as SentencesVC
        sentences.TopicPassed = selectedTopic.heading
    }
}

附带说明一下,在您的命名方案中,请小心并尽量不要在代码中使用大写的变量。 Swift 使用 "camelCase" 约定,大写单词通常保留用于键入名称(类 等)。为清楚起见,您可以将 Topics 重命名为 topics,将 TopicPassed 重命名为 topicPassed,等等