首页 > 解决方案 > 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)
}

标签: iosswiftxcodeuicollectionview

解决方案


替换(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)

推荐阅读