我的要求是首先设置默认颜色getline
,我想根据选择更改颜色。
我的要求是当collectionview首先加载时,背景颜色应为红色,取消选择的颜色为蓝色。 如何管理这个 这是我的代码
access_token = AccessToken.objects.get(token=request.data.get('access_token'), expires__gt=timezone.now())
通过此代码,我的输出是
问题是当我点击第一个indexPath
它有效但通过选择其他我的两种颜色是相同的
答案 0 :(得分:1)
在viewDidLoad
重新加载collectionView
之后,明确选择第一个单元格。
collView.reloadData()
let indexPath = NSIndexPath(forItem: 0, inSection: 0)
collView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: .None)
注意:现在无需在cellForIteamAtIndexPath
内添加颜色更改代码,即可删除该代码。
答案 1 :(得分:1)
如果您的意思是预先选择了第一个单元格,请按照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()
你会弄清楚它是如何运作的。