无法在首次加载屏幕时将集合视图单元格设置为选中

时间:2016-01-09 01:59:43

标签: ios swift swift2 collectionview

我基本上有一个星期几的集合视图,它是基于全局数组设置的。在cellForRowAtIndexPath中,如果在数组中选择了单元格,则单元格将被着色。否则它不会被着色。选择该单元格后,如果之前没有,则应该变为彩色,反之亦然。我遇到的问题是,当我选择一个彩色单元格时,我必须选择它两次才能使它变得无色。这是因为,默认情况下,cell.selected字段为false,因此只需单击一次即可,另一次单击会使其为false并获得所需结果。这就是为什么,在cellForRowAtIndexPath,我决定做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
}

0 个答案:

没有答案