[iOS] UICollectionView의 Cell 위치가 튕기는 현상

민경준·2024년 2월 29일
1

오늘은 작업 중에 collectionView의 cell 위치가 튕기는 현상이 생겨서 이에 대한 삽질 결과를 적어볼 예정이다.

우선 내가 만들어야 하는 결과물은 배달의 민족에서 볼 수 있는 아래와 같은 화면이였다. 스크롤 영역에 들어가 있으며 콜렉션뷰가 배너 역할을 할 수 있는...?

그리고 아래 처럼 스크롤을 아래로 잡아당기면 해당 collectionView의 cell 역시 따라서 Stretchy 되는 autolayout이 필요했다.

어찌저찌 Strechty되는 화면까지는 만들었고, cell 역시 flowLayout의 itemSize 변경을 통해 사이즈가 따라서 변경 되도록 만들었다.

하지만 여기서 문제가 생겼다... 아래로 내릴 때는 괜찮은데 위로 스크롤을 할 때 y축이 틀어져서 통통 튀는듯한 현상이 생겨버림...

view Hierachy로 확인해보니 cell의 y축이 0 아래로 넘어가 버렸음...

어찌저찌 구글링을 통해서 FlowLayout을 서브클래싱 해서 해결하라는건 알았는데... 그 이상을 탐독하기가 어려웠다 ㅠㅅㅠ

그래서 chatGPT 한테 물어봤는데 처음에는 어떤 조건일때 원래의 레이아웃을 무효화 시킬 수 있는지 알려줬다가 cell의 frame을 변경하는 방법을 알려달라고 하니 바로 정답이 튀어나왔다.

ChatGTP야, Cell의 위치는 어떻게 변경할 수 있는거니?

UICollectionViewFlowLayout에서 layoutAttributesForElements(in:) 메서드를 사용하여 cell의 위치를 변경할 수 있습니다. 이 메서드를 오버라이드하여... 어쩌고... 저쩌고...

class CustomFlowLayout: UICollectionViewFlowLayout {

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let superAttributes = super.layoutAttributesForElements(in: rect) else { return nil }

        // 새로운 레이아웃 속성을 복사하여 생성
        var newAttributes = [UICollectionViewLayoutAttributes]()
        
        for attributes in superAttributes {
            // 특정 조건을 만족하면 위치를 변경
            if attributes.representedElementCategory == .cell {
                let modifiedAttributes = attributes.copy() as! UICollectionViewLayoutAttributes
                // 여기에서 원하는 위치 조정 로직을 구현
                // 예를 들어, x좌표를 100만큼 이동
                modifiedAttributes.center.x += 100
                newAttributes.append(modifiedAttributes)
            } else {
                // 다른 유형의 레이아웃은 그대로 유지
                newAttributes.append(attributes)
            }
        }

        return newAttributes
    }
}

크... 이 얼마나 영롱한 코드인가... 바로 적용 ㄱㄱㄱ

캬~ 깔끔하게 흔들림 하나 없는 에이스 침대가 되어버린 나의 collectionView... chat GTP야 니가 나의 구원자가 되어주었구나 고마워....

위에서 flowLayout을 서브 클래싱해야 한다는걸 구글링으로 삽질한 시간 => 1~2시간
chatGPT가 정답을 말하기까지 걸린시간 => 10분

ㅋㅋㅋ여러분 chatGPT 쓰십시오.. 모르는게 없네요 ㅋㅋㅋㅋ

profile
iOS Developer 💻

0개의 댓글