⚠️ 문제: UICollectionView FooterView에 배치한 UIPageControl의 currentPage 변경 불가

FooterView에 배치한 UIPageControl의 currentPage를 변경하고 싶었으나
didSelectItemAt으로는 FooterView 내부에 전달해줄 방법을 찾기 힘들었습니다.
방법이 없지는 않겠지만.. 이번에는 시간이 부족한 관계로 꼼수를 한번 사용해봅시다.
✅ 해결: FooterView 내부 속성을 UICollectionView에서 참조
class GachaCollectionView {
var pageControl: UIPageControl?
...
}
class ViewController {
...
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case "FooterKind":
let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Footer", for: indexPath) as! LegendaryItemFooterView
mainView.gachaCollectionView.pageControl = footerView.pageControl
footerView.pageControl.numberOfPages = switch dataSource[indexPath.section] {
case .first(let items):
items.count / 4
default: 0
}
return footerView
case ...
}
...
}
...
}
UICollectionView인 GachaCollectionView에 pageControl 변수를 선언하였습니다.
이후 ViewController의 viewForSupplementaryElementOfKind 함수에서 FooterView를 설정할 때
GachaCollectionView의 pageControl 변수에 FooterView.pageControl 를 할당합니다.
이제 별도의 코드 없이 GachaCollectionView에서 FooterView의 pageControl에 바로 접근할 수 있습니다.
class GachaCollectionView {
func setLegendaryItemListSection {
...
section.visibleItemsInvalidationHandler = { [weak self] _, contentOffset, environment in
let currentPage = Int(max(0, contentOffset.x / containerSize.width)) // 현재 페이지 = 현재 스크롤 위치(x) / 컬렉션뷰 가로 길이
self?.pageControl?.currentPage = currentPage // 현재 페이지 변경
}
...
}
}
GachaCollectionView의 섹션 설정 코드에서 visibleItemsInvalidationHandler 메서드를 통해
섹션 컨텐츠의 위치가 바뀔 때마다 FooterView의 pageControl에 현재 페이지를 전달할 수 있습니다.
❗️ 위험: 외부에서의 변경 가능성
GachaCollectionView의 pageControl 변수는 internal 접근 제어자로 선언됩니다.
ViewController에서 해당 변수를 할당해주어야하기 때문에 internal 접근제어자를 사용했습니다.
다만, 이 경우 ViewController가 아닌 해당 모듈의 다른 어느곳에서도 GachaCollectionView.pageControl 변수에
접근 가능하므로 예기치못한 변경점이 생길 가능성이 있습니다.
🤔 변수를 private으로 감싸고 메서드로 할당을 하면 어떨까?
class GachaCollectionView { private var pageControl: UIPageControl? func setPageControl(_ comp: UIPageControl) { pageControl = comp } } class ViewController { func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case "FooterKind": let footerView = CollectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Footer", for: indexPAth) as! LegendaryItemFooterView mainView.gachaCollectionView.setPageControl() ... } ... } ... }
메서드를 통한다면 여전히 GachaCollectionView가 참조하고 있는 UIPageControl 자체가 바뀔 가능성은 존재하지만, 할당해둔 UIPageControl의 내부 속성의 변경 위험을 막을 수는 있을 것 같습니다.
'내일배움캠프 > Kiosk - Gacha!' 카테고리의 다른 글
| [트러블 슈팅] UISegmentedControl 배경 색상 설정하기 (0) | 2026.02.10 |
|---|---|
| [트러블 슈팅] UISegmentedControl 이니셜라이저 재정의 (0) | 2026.02.10 |
| [프로젝트 소개] Kiosk 앱 만들기 - Gacha! (0) | 2026.02.10 |