我試圖根據在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
對應
你不能覆蓋擴展方法。對於您的問題,您可以通過在collectionviewcontroller中實現select方法來使用委託方法,並將它們委派給Listviewcontroller。在列表視圖控制器中,您符合委託並編寫代碼。 –
謝謝你的知識。我更新了代碼(和我的問題)以反映這種變化,但代理方法/協議功能仍未被調用。我還能做些什麼來連接兩者? – zachenn
你能分享一些實現嗎?所以我可以看看它謝謝 –