Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SnapKit Constraint update 활용하여 동적 높이 CollectionView 구현 #74

Closed
kimkyuchul opened this issue Jun 27, 2024 · 0 comments
Assignees
Labels

Comments

@kimkyuchul
Copy link
Owner

SnapKit의 Constraint 의 프로퍼티를 생성하고, 버튼 탭 시 collectionView의 ContentSize 만큼 constraint.update하여 높이 레이아웃을 동적으로 변경

// Constraint 타입 선언
private var collectionViewHeightConstraint: Constraint?

  imageCollectionView.snp.makeConstraints {
     $0.top.equalTo(imageTitleLabel.snp.bottom).offset(14)
     $0.leading.trailing.equalToSuperview().inset(12)
     collectionViewHeightConstraint = $0.height.equalTo(Size.UIScreenWidth / 3).constraint
  }
  • makeConstraints 안에서 .constraint로 획득 가능 (동시에 레이아웃도 적용)
        questionTypeButton.backgroundButton.rx.tap
            .asSignal()
            .emit(with: self) { owner, _ in
                owner.dummyImage.append("Dummy")
                owner.imageCollectionView.reloadData()
                
                owner.collectionViewHeightConstraint?.update(offset: owner.imageCollectionView.collectionViewLayout.collectionViewContentSize.height)
                
                owner.view.layoutIfNeeded()
                
            }
            .disposed(by: disposeBag)
            
            
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dummyImage.count
    }
  • 버튼 탭 시 배열에 아이템을 추가 → collectionView의 item이 4개 이상 될 시 2줄로 늘어남 (collectionView의 height를 동적으로 변경해줘야 한다.)
  • Constraint 인스턴스는 위에서 imageCollectionView에 연결되어 있다.
  • Constraint를 업데이트 해주는데 CollectionView.collectionViewLayout.collectionViewContentSize.height 를 활용한다.
  • collectionViewContentSize 는 collectionView의 전체 높이와 너비를 반환한다.
  • collectionViewContentSize 는 언제 할당되는가? -> https://insubkim.tistory.com/337

https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617796-collectionviewcontentsize

https://ios-development.tistory.com/867

@kimkyuchul kimkyuchul added the IOS label Jun 27, 2024
@kimkyuchul kimkyuchul self-assigned this Jun 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant