我试图在我的 Collection View 中允许用户交互。我决定尝试实现 UITapGestureRecognizer 来做到这一点。我尝试将 UITapGestureRecognizer 添加到 CollectionView 本身和 CollectionView 单元格中。这两种方式都会使应用程序崩溃。以下是我将 UITapGestureRecognizer 添加到单元格的方法。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionview.dequeueReusableCell(withReuseIdentifier: "userCell", for: indexPath) as! UserCell
cell.userImage.sd_setImage(with: URL(string: self.user[indexPath.row].imagePath))
cell.nameLabel.text = self.user[indexPath.row].username
cell.userID = self.user[indexPath.row].userID
let singleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "segueToProfile:")
singleTap.numberOfTapsRequired = 1
singleTap.numberOfTouchesRequired = 1
cell.addGestureRecognizer(singleTap)
return cell
}
当我点击单元格时,我会在 AppDelegate 中收到 SIGABRT。错误消息显示“由于未捕获的 NSException 类型异常而终止”。我究竟做错了什么。 UITapGestureRecognizer。
这是我的 segueToProfile 函数:
func segueToProfile(gesture: UITapGestureRecognizer) {
// if(recognizer.state == UIGestureRecognizer.State.ended){
// print("myUIImageView has been tapped by the user.")
// }
print("hell world")
}
最佳答案
如果您使用 collectionView 的 didSelectItemAt
方法,您的代码库看起来可读且可维护。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
currentViewController.performSegue(withIdentifier: "YourSegueName", sender: nil)
}
关于ios - 单击 Collection View 单元格时 UITapGestureRecognizer 崩溃应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59438815/