LoginSignup
1
2

More than 3 years have passed since last update.

UICollectionView Cell color are confusing

Posted at

現象

以下のコードのように、土・日曜を赤くしたいですが、reloadData()すると、
赤い字の場所が混乱している。
Simulator Screen Shot - iPhone Xʀ - 2019-07-11 at 22.53.36.png

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let viewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell",for: indexPath) as! dayCell
        let i = indexPath.row
        if i + 1 < firstWeekday || i + 1 > (daysCount + firstWeekday - 1){
            viewCell.Label.textColor = UIColor.lightGray
        }
        else if i % 7 == 0 || i % 7 == 6 {
            viewCell.Label.textColor = UIColor.red
        }
        return viewCell
    }

原因

UICollectionViewのCellはreusable,なので再生する時使ったCellの属性を残ってしまう。

解決方法

CellのクラスでprepareForReuseメソッドをオーバーライドして毎回Reuse前にデフォルトの設定にする。

import UIKit

class dayCell: UICollectionViewCell {

    @IBOutlet weak var Label: UILabel!
    override func prepareForReuse() {
        super.prepareForReuse()
        Label.textColor = .darkText
    }
}

参考

https://stackoverflow.com/questions/22384992/uicollectionview-reloaddata-changes-cell-order
https://stackoverflow.com/questions/47398944/collectionview-cell-images-are-changing

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2