Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

ios8 - Changing cell background color in UICollectionView in Swift

I am using horizontal collection view to scroll dates. Collection view contain 30 cells. If I select first cell, to indicate the selection, cell background color has been change to brown from default color red. Then, if I select another cell, selected cell color has changed to brown from red. But first cell BGColor remains the same (brown). How can i change to default color by clicking other cell?

       func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath 
   indexPath: NSIndexPath) -> UICollectionViewCell {

    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", 
   forIndexPath: indexPath) as myViewCell

    cell.date_label.text = arr_date[indexPath.item]

    }

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

        var cell = collectionView.cellForItemAtIndexPath(indexPath) as myViewCell

        if(cell.selected)
        {
            cell.backgroundColor = UIColor.brownColor()

        }
        else
        {
            cell.backgroundColor = UIColor.redColor()
        }

    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the function collectionView with the parameter didSelectItemAtIndexPath

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

       let selectedCell:UICollectionViewCell = myCollectionView.cellForItemAtIndexPath(indexPath)!
       selectedCell.contentView.backgroundColor = UIColor(red: 102/256, green: 255/256, blue: 255/256, alpha: 0.66)
}

This creates a constant for the selected UICollectionViewCell, then you just change the background's color


And then for return to the original color when it is deselected, you must use the function collectionView with the parameter didDeselectItemAtIndexPath

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
        let cellToDeselect:UICollectionViewCell = myCollectionView.cellForItemAtIndexPath(indexPath)!
        cellToDeselect.contentView.backgroundColor = UIColor.clearColor()
}

And you change the color to the original one!


For example here is the screenshot from this code in a filterApp

UICollectionView example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...