Bài viết phổ biến của tác giả
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
例如,我有 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
}
}
但它不起作用。我做错了什么?
câu trả lời hay nhất
有一个更简单的解决方案,您已经可以使用 UICollectionView 本身提供的功能。此外,它的性能更好,因为您不必在每次选择单个单元格时都重新加载 collectionView。 Apple 建议您只能在模型实际更改时才使用 reloadData()。
您可以覆盖 UICollectionViewCell 的属性 isSelected
,然后您只需使用属性观察器自定义其外观:
override var isSelected: Bool {
didSet {
if isSelected {
layer.borderWidth = 2
} khác {
layer.borderWidth = 0
}
}
}
请注意,您必须在单元格初始值设定项中或您认为方便的地方设置 layer.borderColor
PS:如果稍后你想做多选,你只需要在collectionView中启用属性allowsMultipleSelection
关于ios - 如何在 didSelect 上向 UICollectionViewCell 添加边框并在选择另一个 UICollectionViewCell 时删除该边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37775839/
Tôi là một lập trình viên xuất sắc, rất giỏi!