我已经在导航 Controller 内设置了一个带有 UICollectionViewCells 的 ViewController。我希望能够单击单元格,然后根据选择的单元格(每个单元格有不同的 Controller )将用户带到一个新的 Controller 。我希望导航栏仍然出现在新 Controller 中,并有一个后退按钮,可以将用户带回到原来的 ViewController。我在初始 View Controller 中有以下代码来设置 Collection View 单元格:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: playlistCellId, for: indexPath) as! playlistCoverCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
我还在 viewDidLoad 中正确注册了单元格。选择单元格时,我使用什么函数来执行操作?
最佳答案
你必须使用:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.row == 0 {
let viewController = UIViewController() // or your custom view controller
self.navigationController?.pushViewController(viewController, animated: true)
}
else if indexPath.row == 1 {
// and so on....
}
}
Tells the delegate that the item at the specified index path was selected. The collection view calls this method when the user successfully selects an item in the collection view. It does not call this method when you programmatically set the selection.
关于ios - 单击 UICollectionViewCell 时如何转换到新 Controller (以编程方式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44036231/