集合视图单元格边框颜色在Swift 3中取消选择

时间:2017-08-25 11:17:54

标签: ios swift3 uicollectionview

使用此代码选择或取消选择集合视图单元格的边框颜色,但它选择边框颜色但不取消选择边框颜色。 我使用了很多代码,但它没有工作。请分享信息

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){

Image2.image = UIImage(named: Images[indexPath.row])

let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderWidth = 2
cell?.layer.borderColor = UIColor.green.cgColor
collectionView.allowsMultipleSelection = false
//        selectedIndexPath = collectionView.indexPathsForSelectedItems!
}

  private func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: IndexPath) {

let cell = collectionView.cellForItem(at: indexPath)
cell?.layer.borderWidth = 2
cell?.layer.borderColor = UIColor.gray.cgColor

}

2 个答案:

答案 0 :(得分:2)

我使用了您的代码它运行良好,但只需从private方法开始删除didDeselectItemAt关键字

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.layer.borderWidth = 2
        cell?.layer.borderColor = UIColor.gray.cgColor
    }

答案 1 :(得分:2)

func collectionView(_collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) { 
    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! DateCell

    cell.layer.borderWidth = 2.0
    cell.layer.borderColor = UIColor.gray.cgColor
}
func collectionView(_collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: IndexPath) {
    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! DateCell

    cell.layer.borderWidth = 2.0
    cell.layer.borderColor = UIColor.gray.cgColor
}

Try This One