Swift UICollectionView 工作奇怪,只注册第二次点击
Posted
技术标签:
【中文标题】Swift UICollectionView 工作奇怪,只注册第二次点击【英文标题】:Swift UICollectionView works strange, registers only second tap 【发布时间】:2019-11-19 18:59:44 【问题描述】:我正在 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)
【问题讨论】:
【参考方案1】:替换(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)
【讨论】:
以上是关于Swift UICollectionView 工作奇怪,只注册第二次点击的主要内容,如果未能解决你的问题,请参考以下文章
如何在滚动swift3时在UICollectionView中隐藏第0行的锁定图像
在 Swift 3 中过滤 UICollectionview 上的结果不起作用?
UICollectionView 中的 viewForSupplementaryElementOfKind 返回 nil 并使用 swift 使应用程序崩溃
Swift UICollectionView 在单击时更新单元格标签而不是实时更新