gpt4 book ai didi

ios - 在 collectionView 单元格上添加边框

转载 作者:搜寻专家 更新时间:2023-11-01 05:47:18 24 4
gpt4 key购买 nike

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

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

现在在 cellForItem 方法中,如果 isSelectedtrue,则必须放置 if else 并使单元格有边框。

这里要注意的是,别忘记放else部分,去掉else部分的border。

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
}

关于ios - 在 collectionView 单元格上添加边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49935711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com