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

时间:2016-06-23 05:15:49

标签: swift2 xcode7

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

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并且可以发送类似参数。

我是如何尝试的:

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发送到goChapter以外的我的func didSelectItemAtIndexPath

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)
}

2 个答案:

答案 0 :(得分:1)

您可以像这样获得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)

希望这有帮助!

答案 1 :(得分:0)

我找到了更简单的解决方案: 在函数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)
}
相关问题