Ios 首次加载屏幕时无法将集合视图单元格设置为“选定”
我基本上有一个每周几天的集合视图,它是基于全局数组设置的。在Ios 首次加载屏幕时无法将集合视图单元格设置为“选定”,ios,swift,swift2,collectionview,Ios,Swift,Swift2,Collectionview,我基本上有一个每周几天的集合视图,它是基于全局数组设置的。在cellforrowatinexpath中,如果在数组中选择该单元格,则该单元格将被着色。否则它将不会着色。当该单元格被选中时,如果之前未被选中,则该单元格应变为彩色,反之亦然。我遇到的问题是,当我选择一个有颜色的单元格时,我必须选择两次才能使其变为无颜色。这是因为默认情况下,单元格.selected字段为false,因此单击一次将其设置为true,单击另一次将其设置为false并获得所需结果。这就是为什么,在cellforrowati
cellforrowatinexpath
中,如果在数组中选择该单元格,则该单元格将被着色。否则它将不会着色。当该单元格被选中时,如果之前未被选中,则该单元格应变为彩色,反之亦然。我遇到的问题是,当我选择一个有颜色的单元格时,我必须选择两次才能使其变为无颜色。这是因为默认情况下,单元格.selected
字段为false,因此单击一次将其设置为true,单击另一次将其设置为false并获得所需结果。这就是为什么,在cellforrowatinexpath
中,我决定做cell.selected=true
,如果事实上,应该选择一周中的某一天,但这似乎也不起作用。有没有人遇到过这个问题或有什么指导?代码如下
@IBOutlet var daysTableView: UICollectionView!
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday"]
var selected = [0,0,0,0,1,0,1]
override func viewDidLoad() {
super.viewDidLoad()
daysTableView.delegate = self
daysTableView.dataSource = self
daysTableView.allowsMultipleSelection = true
// 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, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("days", forIndexPath: indexPath) as! DayCell
cell.day.text = days[indexPath.row]
if (selected[indexPath.row] == 0) {
cell.backgroundColor = UIColor.whiteColor()
cell.selected = false
} else {
cell.backgroundColor = UIColor.redColor()
cell.selected = true
}
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return days.count
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("selected")
selected[indexPath.row] = 1
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! DayCell
cell.backgroundColor = UIColor.redColor()
cell.selected = true
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
print("deselected")
selected[indexPath.row] = 0
let cell = collectionView.cellForItemAtIndexPath(indexPath) as! DayCell
cell.backgroundColor = UIColor.whiteColor()
cell.selected = false
}
您应该发布行为错误的代码部分,以便我们提供帮助。添加一些代码,以便我们能够帮助您实现您的期望。