![](/img/trans.png)
[英]Push viewController from CollectionView cell programmatically not working - swift
[英]Pushing to new ViewController from collectionView Cell didSelectItemAt programmatically - swift
我試圖創建一個簡單的應用程序, UICollectionViewController
編程方式實現UICollectionViewController
。 我創建了一些單元格,當用戶單擊特定單元格時,應將其移至另一個控制器。 但是我面臨着哪個視圖沒有推送到下一個視圖控制器的問題。
這里是我的設置RootViewController的appDelegate
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let flow = UICollectionViewFlowLayout()
let collectionView = ViewController(collectionViewLayout: flow)
let navigation = UINavigationController(rootViewController: collectionView)
window?.rootViewController = navigation
這是我創建UICollectionView
private let cellId = "cellid"
var viewController: ViewController?
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .white
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
// Do any additional setup after loading the view, typically from a nib.
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
cell.backgroundColor = .red
return cell
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 210)
}
這是我如何控制用戶何時點擊特定內容
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(indexPath.item)
viewController?.pushView()
}
func pushView() {
let controller = UINavigationController(rootViewController: DetailController())
self.navigationController?.pushViewController(controller, animated: true)
}
即使函數被調用,但它永遠不會推送到新的視圖控制器
請嘗試以下方法:
let objMainController : yourViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "yourViewController") as! yourViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = objMainController
請從情節提要中嵌入導航控制器。 可能會對您有所幫助。謝謝。
首先,您必須確保當前的視圖控制器具有導航視圖控制器,您可以通過在viewDidLoad方法print(self.navigationViewController)中打印對象來進行檢查。 如果打印為零,則必須使導航控制器執行以下步驟-SelectYourVicotroller->轉到編輯器菜單選項->嵌入到->導航控制器
func pushView() {
let controller = DetailController()
//OR
//Add the storyboard identifier of your view controller - "DetailController"
let controller = self.storyboard.instantiateViewController(withIdentifier: "DetailController") as! DetailController
self.navigationController?.pushViewController(controller, animated:true)
}
將此方法調用為didSelect方法
更改
viewController?.pushView()
至
self.pushView()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.