본문 바로가기
🍎 iOS

[Swift] UICollectionViewCell 안에 UICollectionView 넣기

by 틴디 2020. 9. 29.
728x90
반응형

UICollectionViewCell 또한 타고 타고 올라가다 보면 UIView이기 때문에 기존에 적용한 방식과 똑같이 해주면 됩니다.

완성샷

구성을 보면 주황색 뷰는 3개의 섹션을 가진 UICollectionView이고

초록색

구성을 보면 주황색 뷰는 3개의 섹션을 가진 UICollectionView이고

초록색은 각 섹션에 들어가 있는 하나의 UICollectionViewCell 입니다

그리고 분홍색은 마지막 섹션에 있는 UICollectionViewCell에 UICollectionView를 넣고 sub cell을 구현해 준 모습입니다

 

우선 마지막 줄에 있는 초록색 UICollectionViewCell의 클래스 이름을 

MinutePickerCell 이라고 하고

여기에 분홍색의 UICollectionView를 넣은 뒤

UICollectionViewCell 인 MinutePickerSubCell을 넣어주도록 하겠습니다.

 

우선 커스텀 레이아웃을 만들어 주겠습니다

UICollectionViewFlowLayout은 셀에 대한 위치와 크기 등에 대한 레이아웃을 커스텀할 수 있기 때문에

추후 사용을 위해 클래스를 작성해 줍니다.

 

class PickerFlowLaout: UICollectionViewFlowLayout {
    override init() {
        super.init()
        
        scrollDirection = .horizontal
        minimumLineSpacing = 10
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

 

다음은 MinutePickerCell을 작성해 줍니다

기존에 작성한 대로 UICollectionView 프로퍼티를 작성하고 delegate를 따르게 한 뒤

필요한 설정을 해주면 됩니다. 

class MinutePickerCell: UICollectionViewCell {
    
    let NUMBER_OF_CELL = 60
    let CELL_HEIGHT = 60
    let CELL_IDENTIFIER = "MinutePickerSubCell"
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = #colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1)
        
        let layout = PickerFlowLaout()
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
        collectionView.delegate = self
        collectionView.dataSource = self
        
        self.addSubview(collectionView)
        
        collectionView.register(MinutePickerSubCell.self, forCellWithReuseIdentifier: CELL_IDENTIFIER)
        
        collectionView.backgroundColor = #colorLiteral(red: 0.9098039269, green: 0.4784313738, blue: 0.6431372762, alpha: 1)
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        let constraints = [
            collectionView.topAnchor.constraint(equalTo: self.topAnchor),
            collectionView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            collectionView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
            collectionView.bottomAnchor.constraint(equalTo: self.bottomAnchor)
        ]
        
        NSLayoutConstraint.activate(constraints)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

필요한 상수들을 작성해 주었고

레이아웃에 대한 부분 빼면 기존에 collectionView를 생성한 것과 동일합니다

주의 할 점은 delegate 와 dataSource 잊지 말고 작성해 주어야 하며

register는 cell에 대해 작성하고 적어주어도 무방하지만 먼저 register 적어주었습니다. 

 

extension MinutePickerCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        NUMBER_OF_CELL
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CELL_IDENTIFIER, for: indexPath) as! MinutePickerSubCell
        cell.lblTxt.text = "\(indexPath.row)"
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        CGSize(width: CELL_HEIGHT, height: CELL_HEIGHT)
    }
    
}

 

가독성을 높여 주기 위해 extension으로 클래스를 확장해 주었습니다.

이제 UICollectionViewCell 에 대해 작성해 주겠습니다.

cellForItemAt을 보면 리턴되는 셀이 텍스트 라벨을 가지게 했습니다.

class MinutePickerSubCell: UICollectionViewCell {
    
    var lblTxt = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.layer.borderWidth = 1.0
        self.layer.borderColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        
        self.addSubview(lblTxt)
        
        lblTxt.text = ""
        
        
        lblTxt.translatesAutoresizingMaskIntoConstraints = false
        let constraints = [
            lblTxt.topAnchor.constraint(equalTo: self.topAnchor),
            lblTxt.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            lblTxt.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            lblTxt.trailingAnchor.constraint(equalTo: self.trailingAnchor)
        ]
        
        NSLayoutConstraint.activate(constraints)
        
        lblTxt.textAlignment = .center
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

이렇게 해주면 됩니다.

이상으로 UICollectionViewCell 에 다른 UIView를 넣는 방법을 알아봤습니다~

 

틀리거나 이상한 부분이 있다면 언제든지 댓글로 알려주시면 감사하겠습니다!!

728x90
반응형

댓글