2017-07-28 78 views
0

這是我正在嘗試做的事情。從CollectionViewCell調用NavigationController(以推送另一個視圖控制器)

class UserProfileHeader: UICollectionViewCell { 

    lazy var button: UIButton = { 
     let button = UIButton(type: .system) 
     //... 
     button.addTarget(self, action: #selector(handleButtonTapped), for: touchUpInside) 
     return button 
    }() 

    func handleButtonTapped() { 
     print("action working now") 
     // How to push another vc here? 
    } 

    // ... 
} 

我想調用一個navigationController來在collectionViewCell中推送(顯示)另一個ViewController。我怎樣才能訪問?我試過了,沒有工作。是否因爲MVC模式?細胞不能與其他人交談?或者有什麼辦法可以做到嗎?像使用委託/協議?我對這些事情不太瞭解。

回答

0

創建一個自定義委託並設置其視圖控制器,然後當你的CollectionView單元格按鈕挖掘稱爲是委託方法,它會調用你的ViewController裏面就有你可以把視圖控制器

func handleButtonTapped() { 
//Your delegate method showuld be invoked here 
delegate?.buttontappFromCollectionViewCell() 

} 

//Now inside your view controller 
func buttontappFromCollectionViewCell() { 
let vc = UIStoryboard(name: "storyboardName", bundle: nil).instantiateViewController(withIdentifier: "yourViewControllerIdentifier") 
let navigationController = UINavigationController(rootViewController: vc) 
navigationController.pushViewController(vc, animated: true) 
} 
+0

不知道爲什麼這被拒絕了。 – NRitH

+0

可能是我要求直接從UICollectionViewCell打開storybaord。但最好的辦法是,如果可能的話,總是在ViewController中打開 –

+0

我同意。在故事板中連接一個動作會更容易。 – NRitH

相關問題