개발/Swift
[Swift] Cell 에 init 을 하고싶을때
덤벨로퍼
2022. 8. 16. 16:22
Cell init 에 관해
table cell 이던 collection view cell 이건
cell은 init 할때 parameter를 넣어서 init 할 수가없다.
init(color:UIColor) {
}
그래서 override init 함수를 써야하고 만약 cell 에 속성을 부여하고 싶다면 이런식으로 넣어준다
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ACell", for: indexPath) as? ACell else { fatalError("ACell error")}
cell.color = .red
하지만 reloadData() 가 일어나거나 하면
위의 함수는 한번 더 발생하게 된다.
만약 init()함수 처럼 처음 한번만 발생되기 원한다면
이런 방법이 있다.
private var customInitDone = false
func customInit(color: UIColor) {
if customInitDone { return }
customInitDone = true
self.backgroundColor = color
}
위의 customInit 함수를 cell 생성시에 넣어주면
customInitDone 이 true가 될것이고
cell 이 재사용 될때 cell이 실제로 dispose 되지 않기때문에
customInitDone 이 true로 남아있을것이고
customInit 함수를 return 하여 아래 코드가 실행되지않아
realodData 가 호출되더라도 한번만 불리게된다.