簡體   English   中英

Swift:點擊 UICollectionView 的單元格並打開 AlertViewController

[英]Swift: Click onto cell of UICollectionView and open AlertViewController

在我的應用程序中,我使用的是 UICollectionView。 現在我想開發一個 UIAlertController,當點擊集合視圖的任何單元格時。 我從以下代碼開始:

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

}

但不知何故,“被點擊了!” 從不打印。

嘗試下一個:

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

這是使用委托的版本:

extension HomeViewController: UICollectionViewDelegate {
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("item at \(indexPath.section)/\(indexPath.item) tapped")
  }
}

除了使用擴展,您還可以直接將 UICollectionViewDelegate 和 collectionView(...didSelectItemAt:...) 函數添加到類 HomeViewController 中:

class HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate {
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print("item at \(indexPath.section)/\(indexPath.item) tapped")
  }
}

這是因為您可能在單元格中放置了一些 UIButton。 點擊單元格中的一些空白區域,然后您將獲得“點擊索引”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM