ios - 从 CollectionView didSelect Swift 3 继续移动

标签 ios swift uitableview uicollectionview

在我的代码中

....
class MenuTableViewCell: UITableViewCell {
..
..///some code here
..
}

extension MenuTableViewCell : UICollectionViewDataSource, UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return menuItems.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "menuItemCell", for: indexPath) as! MenuItemViewCell
    cell.menuItemName = menuItems[indexPath.row]

    return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let iconImage  = menuItems[indexPath.row]
    print("iconImage === ",iconImage,section)
    print("Collection view at row \(section) selected index path \(indexPath.row)")

    if (section == 0){
        if(indexPath.row==0) {
            print("inside 0 0")
                 performSegue(withIdentifier: "home", sender: nil)
        }
    }
  }
}

但是它显示了一个错误

使用未解析的标识符“performSegue”

我该怎么做...

最佳答案

好吧,表格 View 单元格没有performSegue 的方法。您需要将消息转发给某个 View Controller 或使 View Controller 成为 Collection View 的数据源。

由于您可能有多个带有 Collection View 的单元格,我建议您使用第一种解决方案(将消息转发给 View Controller )。

所以简单地创建一个委托(delegate):

protocol MenuTableViewCellDelegate: class {
    func menuTableViewCellShouldNavigateHome(_ sender: MenuTableViewCell)
}

在你的单元格中添加一个属性。确保它是弱的:

class MenuTableViewCell: UITableViewCell {
..
    weak var delegate: MenuTableViewCellDelegate?

并在 Collection View 委托(delegate)中调用它:

if(indexPath.row==0) {
    print("inside 0 0")
    delegate?.menuTableViewCellShouldNavigateHome(self)
}

现在在您的 TableView 数据源(我希望它是一个 View Controller )中,在您创建单元格并将自己设置为委托(delegate)的索引路径处找到行的方法单元格

cell.delegate = self
return cell

并实现一个协议(protocol)

extension MyViewController: MenuTableViewCellDelegate {
    func menuTableViewCellShouldNavigateHome(_ sender: MenuTableViewCell) {
        performSegue(withIdentifier: "home", sender: nil)
    }
}

关于ios - 从 CollectionView didSelect Swift 3 继续移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50857481/

相关文章:

ios - 返回 UITableView 的值

ios - 消除 UITableView 下面多余的分隔符

ios - 应用程序将进入后台并进入前台,出现黑屏

ios - 升级到 Swift 3 后,属性 'self.delegate' 未在 super.init 调用中初始化

swift - 在 Swift 中设置 UITextView 文本

swift - MFMailComposeResult 常量不能在 Swift 2.3 中编译

ios - Swift 3 TableView Segue 到多个其他 TableView

ios - Big Nerd Ranch UIKit 导入

ios - 如何关闭 WatchKit 应用

iphone - 无法将类型 'SecTrustResultType' 的值转换为预期参数类型 'UInt32'