如何通过单击集合视图单元格中的按钮导航到另一个视图控制器

How to navigate to another view controller by click on button in collection view cell

我有一个包含多个单元格的集合视图控制器。每个单元格都有一个按钮,我想通过集合视图单元格上的单击按钮导航到另一个视图控制器。我可以通过单击单元格来完成,但我想通过单击单元格中的按钮来完成,而不是通过单击单元格来完成。 我知道如何通过单击单元格来完成,例如:

override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    if let book = books?[indexPath.item] {
        showBookDetail(book)
    }
}

func showBookDetail(book: Book) {
        let layout = UICollectionViewFlowLayout()
        let bookDetailVC = BookDetailVC(collectionViewLayout: layout)
        bookDetailVC.book = book
        navigationController?.pushViewController(bookDetailVC, animated: true)
    }

很简单,因为我有indexPath并且可以发送like参数。

我是怎么做到的:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as! BookCell
    cell.chapter = books?.bookChapters?[indexPath.item]
    cell.goButton.addTarget(self, action: #selector(goChapter), forControlEvents: .TouchUpInside)
    return cell
}

但是如何将 book 发送到 didSelectItemAtIndexPath 之外的我的 func goChapter

func goChapter() {
    let layout = UICollectionViewFlowLayout()
    let bookChapterVC = BookChapterVC(collectionViewLayout: layout)
    bookChapterVC.chapter = self.book?.bookChapters![0] // here I want to send separate chapter of the book
    navigationController?.pushViewController(bookChapterVC, animated: true)
}

您可以通过这种方式获取 UIButton 点击索引:

func goChapter(sender: UIButton!) {
    var point : CGPoint = sender.convertPoint(CGPointZero, toView:collectionView)
    var indexPath = collectionView!.indexPathForItemAtPoint(point)
    bookChapterVC.chapter = self.book?.bookChapters![indexPath.row]
    navigationController?.pushViewController(bookChapterVC, animated: true)
}

如下更新您的 addTarget

cell.goButton.addTarget(self, action: #selector(goChapter(_:)), forControlEvents: .TouchUpInside)

希望对您有所帮助!

我找到了更简单的解决方案: 在函数 cellForItemAtIndexPath

cell.goButton.tag = indexPath.item
cell.goButton.addTarget(self, action: #selector(goChapter), forControlEvents: .TouchUpInside)

然后:

func goChapter(sender: UIButton!) {
    let layout = UICollectionViewFlowLayout()
    let bookChapterVC = BookChapterVC(collectionViewLayout: layout)
    bookChapterVC.chapter = book?.bookChapters![sender.tag]
    navigationController?.pushViewController(bookChapterVC, animated: true)
}