在我的应用程序中,我使用的是 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/