ios - 单击 UICollectionViewCell 时如何转换到新 Controller (以编程方式)

标签 ios swift xcode uicollectionview uicollectionviewcell

我已经在导航 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/

相关文章:

ios - 解除 UISearchBar 键盘后取消按钮消失

objective-c - 当 UIProgressView 已满时加载新 View

ios - 找不到-lyoga的资料库

iphone - 将 NSString 传递给 Webview

ios - 避免在 App Delegate 中重复执行代码

iphone - 存储多个关联在一起的数组的最佳方式 - Objective C

python - 是否有 Swift 等同于 Python 中的 'Filter' 函数?

ios - iOS 应用程序中的过期购买列表

SwiftUI - UI 元素的大小

ios - 我正在尝试将框架/内核集成到 ios 中的简单 .h 和 .m 文件中?