반응형
250x250
05-20 04:02
Today
Total
«   2026/05   »
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
31
Notice
Recent Posts
Recent Comments
Link
Archives
관리 메뉴

Bill Kim's Life...

[iOS] UITableView 셀 재사용 버그 — 데이터가 섞이는 진짜 이유 본문

DEV Tips/iOS

[iOS] UITableView 셀 재사용 버그 — 데이터가 섞이는 진짜 이유

billnjoyce 2026. 3. 22. 20:50
728x90
반응형

개요

iOS에서 매우 흔한 문제:

👉 스크롤하면 셀 데이터가 이상해짐

예:

  • 이미지가 다른 셀에 나타남
  • 체크 상태가 섞임
  • 이전 데이터가 남아있음

의미

UITableView / UICollectionView는:

👉 셀을 새로 만드는 게 아니라 재사용(reuse) 한다

즉,

  • 이전 상태가 그대로 남아있을 수 있음

문제 코드

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    let item = dataList[indexPath.row]

    if item.isSelected {
        cell.backgroundColor = .blue
    }

    return cell
}

👉 문제:

  • isSelected == false일 때 아무 처리 안 함
  • 재사용된 셀 → 이전 색상이 그대로 남음

해결 코드

방법 1: 상태 초기화 (가장 중요)

let item = dataList[indexPath.row]

// 기본 상태 초기화
cell.backgroundColor = .white

if item.isSelected {
    cell.backgroundColor = .blue
}

👉 핵심:

  • 모든 상태를 항상 다시 설정해야 함

방법 2: prepareForReuse 활용

class CustomCell: UITableViewCell {

    override func prepareForReuse() {
        super.prepareForReuse()

        backgroundColor = .white
    }
}

👉 효과:

  • 재사용 시 자동 초기화

방법 3: 비동기 이미지 로딩 주의

cell.imageView?.image = nil // 초기화

loadImage(url: item.imageURL) { image in
    DispatchQueue.main.async {
        cell.imageView?.image = image
    }
}

👉 안 하면:

  • 다른 셀 이미지가 섞여 보임

한 줄 정리

👉 셀은 재사용된다 — 그래서 “항상 초기화”하지 않으면 데이터가 섞인다

728x90
반응형
Comments