在 collectionView 单元格上添加边框

2024-04-29

每次用户单击特定单元格时,该单元格都会有边框。问题是当我来回滚动时,边框会选择随机单元格来设置边框。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.layer.borderColor = UIColor.blue.cgColor
    cell?.layer.borderWidth = 1
}

以防万一您正在寻找 didDeselect 部分

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.layer.borderColor = UIColor.clear.cgColor
    cell?.layer.borderWidth = 1
}

这是因为细胞的可重复使用性。您应该在单元模型中获取属性来跟踪选定的状态 -isSelected: Bool

Now in cellForItem方法,你必须添加 if else 并使你的单元格有边框 ifisSelected is true.

这里请注意,不要忘记放置 else 部分并删除 else 部分中的边框。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.layer.borderColor = UIColor.blue.cgColor
    cell?.layer.borderWidth = 1
    cell?.isSelected = true
}


func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath)
    cell?.layer.borderColor = UIColor.clear.cgColor
    cell?.layer.borderWidth = 1
    cell?.isSelected = false
}


override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
        ...
        ...
        if cell.isSelected {
            //put border logic
        }else {
            // remove border
        }
        return cell
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 collectionView 单元格上添加边框 的相关文章

随机推荐