Swift:UICollectionViewCell didSelectItemAtIndexPath更改backgroundColor

时间:2015-02-19 00:50:13

标签: ios swift uicollectionview uicollectionviewcell

我可以轻松地在CellForItemAtIndexPath方法中更改单元格的背景颜色

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath     indexPath: NSIndexPath) -> UICollectionViewCell {
 cell.backgroundColor = UIColor.blackColor()
 }

但是,当我尝试更改DidSelectItemAtIndexPath中的颜色时,它不起作用。

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath     indexPath: NSIndexPath) {
        let cell: ButtonCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("ButtonCell", forIndexPath: indexPath) as! ButtonCollectionCell {
cell.backgroundColor = UIColor.blackColor()

}

另外我在某处读到使用didSelectItemAtIndexPath不起作用,因为一旦集合视图开始滚动,颜色将改变回来

Swift有什么问题?

非常感谢你的帮助

4 个答案:

答案 0 :(得分:12)

您可以使用此方法:

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){

    var cell : UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
    cell.backgroundColor = UIColor.magentaColor()
}

答案 1 :(得分:9)

老问题,但它可以帮助某人:

无法只是修改单元格,因为当您滚动UICollectionView时,您的更改将会丢失,甚至最差,其他单元格可能会显示错误的背景,因为它们可以重复使用

所以,最好的方法是创建一个NSIndexPath数组并附加你选择的indexPaths:

var selectedIndexes = [NSIndexPath]() {
    didSet {
        collectionView.reloadData()
    }
}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
    // ...
    if let indexSelecionado = selectedIndexes.indexOf(indexPath) {
        selectedIndexes.removeAtIndex(indexSelecionado)
    } else {
        selectedIndexes.append(indexPath)
    }
}

// ...

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    // ...
    if self.selectedIndexes.indexOf(indexPath) == nil {
        cell.backgroundColor = UIColor.whiteColor() // Unselected
    } else {
        cell.backgroundColor = UIColor.redColor() // Selected
    }
    return cell
}

答案 2 :(得分:2)

您可以重写UICollectionViewCell isSelected。它将应用所选方法的更改。

class ButtonCollectionCell: UICollectionViewCell {

            override var isSelected: Bool{
                didSet{
                    if self.isSelected
                    {
                       self.layer.backgroundColor =  colorLiteral(red: 0.8058760762, green: 0.2736578584, blue: 0.1300437152, alpha: 1)

                    }  else
                    {
                       self.layer.backgroundColor =  colorLiteral(red: 0, green: 0, blue: 0, alpha: 0)

                    }
                }
            }

    }

答案 3 :(得分:0)

cell.backgroundColor = UIColor.redColor()

let startTime = DateUtils.getDispatchTimeByDate(NSDate(timeIntervalSinceNow: 0.1))
dispatch_after(startTime, dispatch_get_main_queue()) {[weak self] in
    //there is the code redirect to other viewcontroller
    openOtherVC()
}