Swift:在ViewController中显示名称

时间:2017-07-09 09:51:32

标签: ios swift

我的数组中包含TableViewController的名称,我有ViewController。如果我点击TableViewController中的单元格,我想在ViewController导航栏标题中显示数组中的名称。怎么做?

4 个答案:

答案 0 :(得分:0)

只需在didSelectRowAt()

中写下这个
title = yourArray[indexPath.row]

答案 1 :(得分:0)

如果您使用的是String,并希望导航并传递" title"到 SecondViewController

let c: Character = ""
print(Array(c.unicodeScalars)) // ["\u{0001F1EF}", "\u{0001F1F4}"]

如果您使用Storyboard

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let name = YOUR_ARRAY[indexPath.row]

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    guard let destinationVC = storyboard.instantiateViewController(withIdentifier: "YOUR_SECOND_VIEW_IDENTIFIER") as? SecondViewController else { return}
    destinationVC.title = name
    navigationController?.pushViewController(destinationVC, animated: true)
}

答案 2 :(得分:0)

试试这个:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    tableView.deselectRow(at: indexPath, animated: true)
    navigationItem.title = myArray[indexPath.row]

}

更新:

如果您使用的是故事板,则可以:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    tableView.deselectRow(at: indexPath, animated: true)
    let ame = myArray[indexPath.row]
    performSegue(withIdentifier: "ViewController", sender: selectedName)

}

然后,恢复selectedName中的prepareForSegue并在那里设置destinationVC的标题:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let selectedName = sender as? String,
    let viewController = segue.destination as? ViewController {
      detailViewController.navigationItem.title = selectedName
    }
  }

答案 3 :(得分:0)

你可以通过

设置viewcontroller的标题

假设您有一个视图控制器

class UIViewController{
  // make a variable in your view controller like
 var titleName:String?

 override func viewDidLoad(){
   self.tittle = self.titleName
 }
}
从tableViewController

可以将名称传递给ViewController

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let controller = self.storyboard.instantiateViewController(withIdentifier: "pass you view controller storyboard id here") as! ViewController
controller.titleName = yourArray[indexPath.row]
self.navigationController.pushViewController(controller , animated: true)
    }