iOS - 코드블럭 아카이브
UICollactionView/UITableView를 담은 UIScrollView의 크기를 동적으로 조정해 스크롤하자!
Lia's iOS
2023. 5. 30. 14:34
- 뷰의 반은 일반 view, 나머지 반은 collectionView로 구성되어있는 화면
- collectionView를 포함한 전체 화면이 스크롤되도록 해야 함
- collectionView의 높이만큼 scrollView를 설정해 전체 collectionView의 모든 cell이 scrollView에서 보일 수 있도록 구현
이 때, contentView는 addSubView까지만 하고 constraints는 잡아주지 않는다.
// 스크롤뷰 기본 설정 - 충분한 높이로 임의로 설정
scrollView.contentSize = CGSize(width: scrollView.frame.width, height: 1200)
contentView.frame = CGRect(x: 0, y: 0, width: scrollView.frame.width, height: 1200)
// 스크롤뷰 높이 조정 (컬렉션뷰 동적 높이 + 그외 view 고정 높이)
func updateScrollViewHeight() {
let newHeight = collectionView.collectionViewLayout.collectionViewContentSize.height + 400
scrollView.contentSize = CGSize(width: scrollView.frame.width, height: newHeight)
contentView.frame = CGRect(x: 0, y: 0, width: scrollView.frame.width, height: newHeight)
}
// 마지막 cell을 그릴 때 updateScrollViewHeight를 호출해 scrollView 높이 줄이기
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RDFilterCollectionViewCell.identifier, for: indexPath) as? RDFilterCollectionViewCell else { return UICollectionViewCell() }
if indexPath.section == yourLastSection && indexPath.item == yourLastItem {
updateScrollViewHeight()
}
return cell
}
혹은!!!!!!!!
tableView를 담은 특수한 경우는 고려하지 않았을 때에는, contentSize나 frame을 직접 설정하지 않고 contentView의 constraints를 아래처럼 잡아주어도 된다.
contentView.snp.makeConstraints { (make) in
make.width.equalToSuperview()
make.centerX.top.bottom.equalToSuperview()
}