iOS) delegate 에 여러개의 컬렉션뷰를 연결하기

less than 1 minute read

delegate 에 여러개의 컬렉션뷰를 연결하기

컬렉션뷰를 구분해서 각각 다르게 설정해주고 싶었다. 총 두가지 방법이 있다.

  1. collectionView == ... 과 같이 내가 원하는 뷰일때 라는 조건문을 사용한다.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if collectionView == bandCollectionView {
        guard let bandCell = bandCollectionView.dequeueReusableCell(withReuseIdentifier: "BandCollectionViewCell", for: indexPath) as? BandCollectionViewCell else {
            return UICollectionViewCell()
        }
        
        return bandCell
    } else if collectionView == missionCollectionView {
        guard let missionCell = missionCollectionView.dequeueReusableCell(withReuseIdentifier: "MissionCollectionViewCell", for: indexPath) as? MissionCollectionViewCell else {
            return UICollectionViewCell()
        }
        
        return missionCell
    } else if collectionView == pageCollectionView {
        guard let pageCell = pageCollectionView.dequeueReusableCell(withReuseIdentifier: "PageCollectionViewCell", for: indexPath) as? PageCollectionViewCell else {
            return UICollectionViewCell()
        }
        pageCell.initializeData(pageList[indexPath.row].pageImage, pageList[indexPath.row].title, pageList[indexPath.row].detail, pageList[indexPath.row].subscribe)
        
        return pageCell
    } else {
        guard let topicCell = topicCollectionView.dequeueReusableCell(withReuseIdentifier: "TopicCollectionViewCell", for: indexPath) as? TopicCollectionViewCell else {
            return UICollectionViewCell()
        }
        topicCell.initializeData(topicList[indexPath.row])
        
        return topicCell
    }
}
  1. tag 를 사용한다.
override func viewDedLoad() {
    super.viewDidLoad()
    //...
    bandCollectionView.tag = 1
    bandCollectionView.tag = 2
    bandCollectionView.tag = 3
    bandCollectionView.tag = 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     if collectionView.tag = 1 {
     //...
     }else  if collectionView.tag = 2 {
     //...
     }else  if collectionView.tag = 3 {
     //...
     } else {
     //...
     }
}

총 4개의 커스텀 컬렉션 뷰를 설정

출처

출처ㅣhttps://zeddios.tistory.com/169

Categories:

Updated: