Infinite CollectionView
by Seoyeong
CollectionView 를 이용한 무한 페이징 코드입니다.
let arrays = ["a", "b", "c', "d"]
갯수는 arrays + 4 개를 할당합니다.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrays.count + 4
}
사이즈는 원하는 대로
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = UIApplication.screenWidth() - 32.0
let height: CGFloat = (UIApplication.screenWidth() - 32.0) * 100.0/343.0
return CGSize(width: width, height: height)
}
Cell에 데이터를 할당하는 부분인데 여기서는 앞 2개를 마지막 데이터, 뒤 2개를 0번째 데이터를 넣습니다. Index로 표현하면 ( 4, 4, 0, 1, 2, 3, 4, 0, 0 ) 이런식으로
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collection.dequeueReusableCell(withReuseIdentifier: "SlideImageCell", for: indexPath) as? SlideImageCell else {
return UICollectionViewCell()
}
if indexPath.row == 0 || indexPath.row == 1 {
cell.label.text = arrays[arrays.count - 1]
} else if indexPath.row == arrays.count + 2 || indexPath.row == arrays.count + 3 {
cell.label.text = arrays[0]
} else {
let row = indexPath.row - 2
cell.label.text = arrays[row]
}
return cell
}
이 코드는 Cell 간의 간격을 0으로 만들어주는 코드입니다.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
willDisplay를 이용하여 마지막 셀로 이동하는 순간 바로 indexPath.row = 2인 셀로 이동을 하고 반대로 처음 셀로 이동하는 순간에는 indexPath.row = arrays.count + 1 로 이동합니다.
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.row == arrays.count + 3 {
collection.scrollToItem(at: IndexPath(item: 2, section: 0), at: .left, animated: false)
}
if indexPath.row == 0 {
collection.scrollToItem(at: IndexPath(item: arrays.count+1, section: 0), at: .right, animated: false)
}
}
앞뒤로 1개씩이 아닌 2개씩 주는 이유는 willDisplay 함수가 셀을 이동하기 전에 호출이 되어 애니메이션이 자연스럽지 않아 1번은 자연스럽게 이동하고 다음 2번은 바로 화면이 전환 되는 식으로 하기 위해 2개를 주었습니다.
아마 이부분은 추가로 수정해야할것 같습니다.
Subscribe via RSS