Rex*_*xha 2 ios uicollectionview swift
我想向 my 添加一个点击事件CollectionViewCell,并将 my 的cell数据传递到那里。我怎样才能实现这个目标?该事件应该由 my 处理ViewController还是由 处理CollectionViewCell?
我的ViewController:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
cell.imgImage.image = imageArray[indexPath.row]
cell.url = "xhini"
return cell
}
Run Code Online (Sandbox Code Playgroud)
我的CollectionViewCell:
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imgImage: UIImageView!
var url: String = "url"
}
Run Code Online (Sandbox Code Playgroud)
实施UICollectionViewDelegate,然后您可以使用以下方法来对ViewController选择单元格做出反应:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let image = imageArray[indexPath.row]
// do stuff with image, or with other data that you need
}
Run Code Online (Sandbox Code Playgroud)
不要忘记在设置数据源的地方设置委托:
collectionView.dataSource = self
// add this line:
collectionView.delegate = self
Run Code Online (Sandbox Code Playgroud)
更新
或者,如果您正在使用情节提要,您希望使用情节提要设置它,就像设置数据源dataSource一样tableView:
更新2
您的tap手势识别器取消了集合视图的事件,因此要处理此问题,只需取消注释该行即可tap.cancelsTouchesInView = false,它将起作用:
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7804 次 |
| 最近记录: |