委托方法更改navigationItem.titleView不起作用
我试图根据在CollectionViewController
中选择的行更改ListViewController
的navigationItem.titleView
。我正在尝试使用委托方法执行此操作,但它不起作用。正在调用didSelectRowAt
,但从未调用func changeTitleView
。我不确定有什么问题。当我使用CollectionViewController
中的func changeTitleView
并在其自己的类中使用它时,它可以工作,所以我知道该功能正在工作。我只是不完全确定如何将从CollectionVC
选择的String
数据传递给ListVC
。我对委托方法很陌生。委托方法更改navigationItem.titleView不起作用
全局变量:
var selectedCollection: CollectionItem?
CollectionViewController:
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!)
}
}
ListViewController:
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)
}
}
我明白任何帮助,您可以提供给我。提前致谢。
UPDATE
我通过名为MenuTableViewController
侧菜单实例化CollectionViewController
。我现在意识到我需要产业链的委托方法,但是,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)
我也不太清楚如何设置的委托方法时,这种情况下
UPDATE
的委托方法的工作,当我presen t CollectionViewController
但不是CollectionViewControllerNav
对应
扩展不能/不应该重写。
无法覆盖扩展中的功能(如属性或方法),如Apple的Swift指南中所述。
Extensions can add new functionality to a type, but they cannot override existing functionality.
Apple Developer Guide
编译器允许您在扩展中重写与Objective-C的兼容性。但它实际上违反了语言指令。
而不是exSend CollectionViewcontroller for didSelectrow。你应该实现didSelectRow方法是CollectionViewController
你不能覆盖扩展方法。对于您的问题,您可以通过在collectionviewcontroller中实现select方法来使用委托方法,并将它们委派给Listviewcontroller。在列表视图控制器中,您符合委托并编写代码。 –
谢谢你的知识。我更新了代码(和我的问题)以反映这种变化,但代理方法/协议功能仍未被调用。我还能做些什么来连接两者? – zachenn
你能分享一些实现吗?所以我可以看看它谢谢 –