委托方法更改navigationItem.titleView无法正常工作

时间:2017-10-08 09:06:31

标签: ios swift uinavigationcontroller delegates

我正在尝试根据ListViewController中选择的行更改navigationItem.titleView的{​​{1}}。我试图使用委托方法,但它无法正常工作。正在调用CollectionViewController,但是didSelectRowAt永远不会被调用。我不确定是什么问题。当我在func changeTitleView内使用func changeTitleView并在其自己的类中使用它时,它可以工作,所以我知道函数正在运行。我不完全确定如何将CollectionViewController中选择的String数据传递给CollectionVC。我对委托方法很新。

全局变量:

ListVC

CollectionViewController:

var selectedCollection: CollectionItem?

ListViewController:

protocol HandleTitleView {
  func doesThisWork(answer: String)
}

class CollectionViewController: UITableViewController {

  var handleTitleViewDelegate: HandleTitleView? = nil

  override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let selectedItem = collections[indexPath.row]
    selectedCollection = selectedItem
    let title = selectedCollection?.collectionTitle

    handleTitleViewDelegate?.doesThisWork(answer: title!)
  }
}

感谢您提供给我的任何帮助。提前谢谢。

更新

我通过名为class ListViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // set up the collectionViewDelegate let collectionViewController = storyboard?.instantiateViewController(withIdentifier: "CollectionViewController") as! CollectionViewController collectionViewController.titleView = titleLabel collectionViewController.handleTitleViewDelegate = self } extension ListViewController: HandleTitleView { func doesThisWork(answer: String) { print(answer) } } 的侧边菜单实例化CollectionViewController。我现在意识到我需要链接委托方法,但是MenuTableViewController嵌入在导航栏中,因此当我实例化它时,我必须实例化CollectionViewController并且无法将CollectionViewControllerNav设置为MenuTableViewController代表:

CollectionVC

我不确定在这种情况下如何设置委托方法

更新

当我呈现override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: let collectionViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CollectionViewController") as! CollectionViewController collectionViewController.handleTitleViewDelegate = self let collectionViewControllerNav = storyboard?.instantiateViewController(withIdentifier: "CollectionViewControllerNav") self.present(collectionViewControllerNav!, animated: true, completion: nil) 而不是CollectionViewController对应

时,委托方法有效

1 个答案:

答案 0 :(得分:0)

扩展程序不能/不应该覆盖。

如Apple的Swift指南中所述,无法覆盖扩展中的功能(如属性或方法)。

Extensions can add new functionality to a type, but they cannot override existing functionality.
Apple Developer Guide

编译器允许您在扩展中覆盖以与Objective-C兼容。但它实际上违反了语言指令。

而不是针对didSelectrow的extennd CollectionViewcontroller。你应该实现didSelectRow方法是CollectionViewController