2016-06-23 18 views
1

私はいくつかのセルを持つコレクションビューコントローラを持っています。各セルにはボタンがあり、コレクションビューセルの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 
} 

をどのように私のFUNC goChapterdidSelectItemAtIndexPathbookを送信するために:

どのように私はそれをしようか?あなたはUIButtonは、この方法のようにインデックスをクリック得ることができます

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

答えて

1

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

をはい、それは動作します。ありがとう! – andrey

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) 
} 
関連する問題