ios - UICollectionView 单元格选择的奇怪行为

标签 ios swift uicollectionview

我目前有这个(伪)代码:

var selectedCell: UICollectionViewCell?

override func viewDidLoad() {
    super.viewDidLoad()
    ...
    #initialize all objects and pull data from the server to fill the cells

    UIView.animate(withDuration: 0, animations: {
        self.dataCollectionView.reloadData()
    }, completion: {(finished) in

        let indexPath = IndexPath(row: 0, section: 0)
        self.dataCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .top)
        self.collectionView(self.dataCollectionView, didSelectItemAt: indexPath)
    })
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! DataCollectionViewCell
    if !selectedCell {
        cell.layer.borderWidth = 1
    }
    else {
       cell.layer.borderWidth = 2            
    }
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAtindexPath: IndexPath) {

    let cell = collectionView.cellForItem(at: indexPath)
    selectedCell = cell
    cell.image = SomeImageFromServer
    cell.layer.borderWidth = 2
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {

    let cell = collectionView.cellForItem(at: indexPath)
    cell.layer.borderWidth = 1
}

我的想法是这段代码将在 Collection View 加载后立即选择第一个单元格,它确实如此。问题是它也选择了最后一个单元格,但是从不为最后一个单元格调用 didSelectItemAtindexPath,而只为第一个单元格调用。

我尝试使用 let indexPath = IndexPath(row: 1, section: 0) 选择第二个单元格,一旦加载了 collectionview,它确实选择了第二个单元格,最后一个没有像您想象的那样选择单元格。

一旦选择了任何一个单元格,最后一个单元格将被取消选择。

所以我的假设是,这不是认为单元格被“选中”的代码,而是出于某种原因为所选单元格提供“选定单元格边框”,但仅当第一个选中的单元格是第一个时。有什么想法吗?

最佳答案

尝试将边框设置移动到单元格中,UICollectionView 将自动管理边框宽度:

//Swift3
class TestCollectionViewCell: UICollectionViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()

        self.layer.borderWidth = 1 //Default border width
    }

    override var isSelected: Bool {
        didSet{
            if self.isSelected {
                self.layer.borderWidth = 2
            }
            else{
                self.layer.borderWidth = 1
            }
        }
    }
}

关于ios - UICollectionView 单元格选择的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41868085/

相关文章:

ios - Swift - 以编程方式更改 UICollectionViewCell 大小

ios - 使用 FB iOS SDK 发布到 friend 提要时出错

ios - 单击 UICollectionView 单元格中的 WKWebView 会导致未调用回调

c# - 为什么要更改后退按钮的标题?

json - SwiftyJSON-迭代具有 ID 的非数组对象

swift - collectionView.reloadData 无法正常运行

swift - 在 Swift 中正确格式化 NSTimer

ios - UICollectionView:ScrollToItem 到中心单元格在水平 Collection View 上不起作用

ios - 在动态值 TableView 中使用 performSeguewithIdentifier 函数

ios - Ad Hoc 发行版 Xcode 10,应用程序无法正常工作