我的要求是首先设置默认颜色indexPath
我想根据选择改变颜色。
我的要求是当集合视图在第一个索引加载时背景颜色应该是红色。未选择的颜色是蓝色。
如何管理这个
这是我的代码
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
它有效,但通过选择其他颜色我的两种颜色是相同的
In your viewDidLoad
重新加载collectionView
然后像这样明确选择第一个单元格。
collView.reloadData()
let indexPath = NSIndexPath(forItem: 0, inSection: 0)
collView.selectItemAtIndexPath(indexPath, animated: true, scrollPosition: .None)
Note :现在无需在您的内部添加颜色更改代码cellForIteamAtIndexPath
删除该代码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)