Swift:点击UICollectionView的单元格并打开AlertViewController
在我的应用程序中,我使用的是UICollectionView。现在我想开发一个UIAlertController,点击集合视图中的任何单元格。 我开始用下面的代码: “GOT点击”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!")
}
}
但不知何故,从不打印。
下一个尝试:
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)!")
}
}
感谢您的回答:)我现在将使用第二个版本。您能否告诉我如何将轻拍单元格的索引从轻击功能传递到 func collectionView(_ collectionView:UICollectionView,cellForItemAt indexPath:IndexPath) - > UICollectionViewCell ? –
你不需要这样做。您在每个单元格中添加手势识别器,并且当您选择其中一个单元格时,在方法点击(_ :)中获得索引。如果你想改变你选择的单元格,你可以使用下面的代码来使用这个单元格:let cell = self.messageCollectionView.cellForItem(at:index) –
谢谢! –
你设置委托和数据源? – ronatory
不,我该怎么做?对不起,我是初学者:D –
@ AlexanderJeitler-Stehr,知道你已经开始iOS和学习Swift,这真是太好了。你只是错过添加** UICollectionViewDelegate **到扩展。只需在** UICollectionViewDataSource **之后添加它,您就可以轻松前往。确保你已经将委托绑定到'HomeViewController'。快乐编码:) –