2016-06-12 33 views
3

たとえば、10個のセルを持つUICollectionView。選択したセルに境界線を追加し、後で別のセルを選択し、前の境界線を削除して、新しい選択セルに境界線を追加したいとします。didSelectでUICollectionViewCellにボーダーを追加する方法、別のUICollectionViewCellを選択してそのボーダーを削除する?

どうすればこの問題を解決できますか?

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

をしかし、それは動作しません:

私はこれを試してみました。私は間違っている?

答えて

2

現在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 
} 
1

スウィフト3バージョン:

func collectionView(_ collectionView: UICollectionView, 
        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 

     var borderColor: CGColor! = UIColor.clear.cgColor 
     var borderWidth: CGFloat = 0 

     if indexPath == selectedIndexPath{ 
      borderColor = UIColor.brown.cgColor 
      borderWidth = 1 //or whatever you please 
     }else{ 
      borderColor = UIColor.clear.cgColor 
      borderWidth = 0 
     } 

     cell.imageView.layer.borderWidth = borderWidth 
     cell.imageView.layer.borderColor = borderColor 

    } 
関連する問題