在Collectionview中如何根据select设置颜色?
我的要求是设置默认颜色在第一个indexPath
,我想改变颜色根据select。
我的要求是当collectionview在第一次加载索引时,背景颜色应该是红色,而取消select的颜色是蓝色。 如何pipe理这是我的代码
import UIKit class MyCollectionViewCell: UICollectionViewCell { override var selected: Bool { didSet { contentView.backgroundColor = selected ? UIColor.redColor(): UIColor.blueColor() } } } class ViewController: UIViewController { @IBOutlet var collView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 5 } // make a cell for each cell index path func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // get a reference to our storyboard cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCollectionViewCell", forIndexPath: indexPath) as! MyCollectionViewCell if(indexPath.row == 0) { //for first cell in the collection cell.backgroundColor = UIColor.redColor() } else { cell.backgroundColor = UIColor.blueColor() } return cell } }
通过这个代码我的输出是
问题是当我点击第一个indexPath
它的作品,但通过select其他人我的两种颜色是相同的
在你的viewDidLoad
重新加载collectionView
之后,明确地select这样的第一个单元格。
collView.reloadData() let indexPath = NSIndexPath(forItem: 0, inSection: 0) collView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: .None)
注意:现在不需要在cellForIteamAtIndexPath
中添加更改颜色的代码,就可以删除这些代码。
如果你的意思是你已经预先选好你的第一个单元 ,那么按照NDOC的答案。
只是更好的解释你的方法:
在cellForItemAt
方法中:
if(indexPath.row == 0) { //for first cell in the collection cell.backgroundColor = UIColor.redColor() //this is the color of the first row } else { cell.backgroundColor = UIColor.blueColor() //this is the color of the other rows }
在MyCollectionViewCell
子类中:
//if any cell (first or other) is selected, it's bg color will be red //if any cell will be deselected, it's bg color will be blue didSet { contentView.backgroundColor = selected ? UIColor.redColor(): UIColor.blueColor() }
它可能会让你困惑,所以把这行代码改成
contentView.backgroundColor = selected ? UIColor.yellowColor(): UIColor.greenColor()
你会发现,它是如何工作的。