ios - Swift UICollectionView 工作奇怪,只注册第二次点击
问题描述
我在 Xcode 11 项目中实现了一个集合视图,发生的情况是只有第二次点击被注册。当用户点击左侧单元格时,它不会打开详细信息屏幕,当用户接下来点击右侧单元格时,左侧单元格会打开,这是非常奇怪的行为。我不使用故事板只是编程方法。这是我的代码:
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.register(CustomCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
return cv
}()
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 150, height: 150)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return myData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell
cell.backgroundColor = .white
cell.data = myData[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let newViewController = SecondViewController(data: myData[indexPath.item])
self.navigationController?.pushViewController(SecondViewController, animated: true)
}
解决方案
替换(didDeselectItemAt
不是didSelectItemAt
)
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
和
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
也应该是
let newViewController = SecondViewController(data: myData[indexPath.item])
self.navigationController?.pushViewController(newViewController, animated: true)
推荐阅读
- angular - 尝试添加自动映射器的 Visual Studio 角度模板
- flutter - 颤振/飞镖抽象类中的工厂方法
- javascript - 有条件地将数据包装在与 vue 的链接中
- c++ - 单独地,std::getline() 工作正常,但如果事先有输入,则输出行为异常
- autofill - xlwings 和自动填充脚本
- tableau-api - 计算字段影响 Tableau 中的总计
- iis - KB5005043 影响解密 web.config?
- c# - C# VSIX 模板:尝试使用自定义向导会导致程序集引用错误
- kubernetes - 在 minikube 中从 yaml 文件创建部署
- python - For循环和嵌套If语句比较,Python中的简化