UICollectionView Cell color are confusing

현상.


다음 코드와 같이 토요일과 일요일을 붉히고 싶습니다. 만약reloadData () 라면
빨간 글자가 난잡하다.
  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의 반에서 prepareForeuse 방법을 다시 쓰고, 매번 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

좋은 웹페이지 즐겨찾기