ios - Swift:单击 UICollectionView 的单元格并打开 AlertViewController

标签 ios swift uicollectionview click

在我的应用程序中,我使用的是 UICollectionView。现在我想开发一个 UIAlertController,当点击 Collection View 的任何单元格时。 我从以下代码开始:

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

关于ios - Swift:单击 UICollectionView 的单元格并打开 AlertViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46987928/

相关文章:

ios - 在调用初始 ViewController ViewDidLoad 时,CoreData 和 NSUserDefaults 会一直加载吗?

ios - 如何根据 segmentedControl 索引更改数据

ios - 如何等待查询完成加载 Collection View

ios - AVAsset 不适用于本地文件

ios - 从 Swift 中的 SKSpriteNode 子类更新 SKScene 中保存的游戏分数

ios - Storyboard - 以编程方式隐藏导航 Controller 的顶部栏

iphone - Webview 不会返回到原始页面

swift - Collection View 上的多项选择

swift - searchBar 函数但是 TableView fatal error

ios - 在 UICollectionView swift 中获取单元格 onClick 的所有 subview