2017-10-28 4 views
1

私のアプリでは、UICollectionViewを使用しています。コレクションビューの任意のセルをクリックすると、UIAlertControllerを開発したいと思います。 私は次のコードで開始:Swift:UICollectionViewのセルをクリックし、AlertViewControllerを開きます。

extension HomeViewController: UICollectionViewDataSource { 

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 
    … 
} 

// specify cells 
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    …. 
} 

// called when widget is moved 
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { 
     … 
} 

// called when clicked 
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 
    print("Got clicked!") 
} 

} 

しかし、どういうわけか、 "クリックされました!"決して印刷されません。

+0

デリゲートとデータソースを設定しましたか? – ronatory

+0

いいえ、どうすればいいですか?申し訳ありません、私は初心者です:D –

+0

@ AlexanderJeitler-Stehr、あなたがiOSを始め、Swiftを学んだことを知ってうれしいです。エクステンションに** UICollectionViewDelegate **を追加することができません。 ** UICollectionViewDataSource **の後に追加するだけでいいです。デリゲートを 'HomeViewController'にバインドしたことを確認してください。ハッピーコーディング:) –

答えて

1

は、次の試してみてください。

extension HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate { 

} 

または

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
    ... 
    cell.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap(_:)))) 
} 

func tap(_ sender: UITapGestureRecognizer) { 

    let location = sender.location(in: self.collectionView) 
    let indexPath = self.collectionView.indexPathForItem(at: location) 

    if let index = indexPath {  
     print("Got clicked on index: \(index)!") 
    }   
} 
+0

あなたの答えをありがとう:)私は今、2番目のバージョンを使用します。タップ関数のタップされたセルのインデックスを、 func collectionView(_ collectionView:UICollectionView、cellForItemAt indexPath:IndexPath) - > UICollectionViewCell に渡す方法を教えてください。 –

+0

あなたはそれをする必要はありません。各セルにジェスチャ認識機能を追加し、セルの1つを選択すると、メソッドタップ(_ :)でインデックスを取得します。選択したセルを変更したい場合は、次のコードを使用してこのセルを使用します。let cell = self.messageCollectionView.cellForItem(at:index) –

+0

ありがとうございました! –

関連する問題