티스토리 뷰

화면의 구조를 생각하다보면 collectionViewCell의 내부에 collectionView를 구현하는 경우가 생긴다.

이럴때 발생한 삽질에 대해 끄적거려보려고 한다.


// collectionView 클래스
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Cell
    cell.data = dataList[indexPath.row]        // cell에 데이터 넘겨주는 코드...
    return cell
}

보통 위와 같이 cell 인스턴스를 만들고 데이터를 넘겨주었다.

그 후에 아래와 같이 cell 내부의 collectionView에서 같은 방식으로 cellForItemAt 메서드를 호출하여 cell을 생성해서 리턴해주었다.

// collectionViewCell 내부에 구현한 또 하나의 collectionView
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let innerCell = collectionView.dequeueReusableCell(withReuseIdentifier: "innerCell", for: indexPath) as! InnerCell
    // innerCell에 데이터 세팅하는 코드...
    return innerCell
}

하지만 여기서 문제가 생겼다.

collectionView에서는 스크롤할 때, cell 인스턴스를 항상 생성하지 않고 재사용한다. 

그러다보니 init() 메서드나 awakeFromNib() 메서드가 호출되지 않아서 collectionView의 cellForItemAt  메서드 또한 호출되지 않는 현상이 있었다.

결과적으로 데이터가 이상하게 엉키게 되는 현상을 볼 수 있었다....


그래서 간단하게 <데이터를 넘겨주는 코드> 부분에 collectionView를 reload하는 방식으로 해결했다.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Cell
    cell.data = dataList[indexPath.row]
    cell.collectionView.reloadData()
    return cell
}

가장 상단 코드에서 reload하는 코드 한줄만 추가되었다.

더 좋은 방법이 생각나면 다시 포스팅 해야겠다... 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함