Joh*_*ohn 7 ios uicollectionview uicollectionviewcell swift
例如,我有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
}
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用.我做错了什么?
小智 7
有一个更简单的解决方案,您已经可以使用 UICollectionView 本身提供的功能。此外,它的性能更好,因为您不必每次选择单个单元格时都重新加载 collectionView。Apple 建议您只能在模型实际更改时使用 reloadData()。
您可以覆盖isSelected
UICollectionViewCell的属性,然后您只需使用属性观察器自定义其外观:
override var isSelected: Bool {
didSet {
if isSelected {
layer.borderWidth = 2
} else {
layer.borderWidth = 0
}
}
}
Run Code Online (Sandbox Code Playgroud)
只是提醒您必须layer.borderColor
在单元格初始化程序中或您认为方便的地方进行设置
PS:如果以后你想做多选,你只需要allowsMultipleSelection
在collectionView中启用该属性
您可以将所选内容保存indexPath
到变量中并cellForItemAtIndexPath
检查当前indexPath
是否等于所选索引路径(您需要在collectionView
每次选中时重新加载)
var selectedIndexPath: NSIndexPath{
didSet{
collectionView.reloadData()
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
selectedIndexPath = indexPath
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var borderColor: CGColor! = UIColor.clearColor().CGColor
var borderWidth: CGFloat = 0
if indexPath == selectedIndexPath{
borderColor = UIColor.brownColor().CGColor
borderWidth = 1 //or whatever you please
}else{
borderColor = UIColor.clearColor().CGColor
borderWidth = 0
}
cell.imageView.layer.borderWidth = borderWidth
cell.imageView.layer.borderColor = borderColor
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7962 次 |
最近记录: |