gpt4 book ai didi

ios - 如何在 didSelect 上向 UICollectionViewCell 添加边框并在选择另一个 UICollectionViewCell 时删除该边框?

转载 作者:搜寻专家 更新时间:2023-10-30 21:55:09 36 4
gpt4 key购买 nike

例如,我有 10 个单元格的 UICollectionView。我想为选定的单元格添加边框,稍后,在选择另一个单元格时,想要删除以前的边框并为新的选定单元格添加边框。

我怎样才能做到这一点?

我已经试过了:

var selected = [NSIndexPath]()
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.imageView.image = applyFilter(self.colorCubeFilterFromLUT("\(self.LUTs[indexPath.row])")!, image: self.image!)

self.selected.append(indexPath)
}

func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
let cell = self.filtersCollectionView.cellForItemAtIndexPath(indexPath) as! FiltersCollectionViewCell
cell.imageView.layer.borderWidth = 3.0
cell.imageView.layer.borderColor = UIColor.brownColor().CGColor
}

func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {

if self.selected.count > 1 && indexPath == self.selected[self.selected.count - 1] {
let cell = self.filtersCollectionView.cellForItemAtIndexPath(indexPath) as! FiltersCollectionViewCell
cell.imageView.layer.borderWidth = 0.0
cell.imageView.layer.borderColor = UIColor.clearColor().CGColor
}
}

但它不起作用。我做错了什么?

最佳答案

有一个更简单的解决方案,您已经可以使用 UICollectionView 本身提供的功能。此外,它的性能更好,因为您不必在每次选择单个单元格时都重新加载 collectionView。 Apple 建议您只能在模型实际更改时才使用 reloadData()。

您可以覆盖 UICollectionViewCell 的属性 isSelected,然后您只需使用属性观察器自定义其外观:

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

请注意,您必须在单元格初始值设定项中或您认为方便的地方设置 layer.borderColor

PS:如果稍后你想做多选,你只需要在collectionView中启用属性allowsMultipleSelection

关于ios - 如何在 didSelect 上向 UICollectionViewCell 添加边框并在选择另一个 UICollectionViewCell 时删除该边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37775839/

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