我有几个单元格的集合视图控制器。每个单元格都有一个按钮,我想通过单击集合视图单元格上的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
到我的funcgoChapter
外面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)
}
您可以通过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)
希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句