我以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
    }
}

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

最佳答案

您可以将所选的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
}

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

10-10 18:28
查看更多