개발하는 동글 :]

[TIL],[UIkit] 컬렉션 뷰(Collection View) 본문

카테고리 없음

[TIL],[UIkit] 컬렉션 뷰(Collection View)

동글하다 2023. 7. 18. 10:12

CollectionView를 사용하는 순서

UICollectionView 타입의 속성을 하나 생성한다.

let slideView: UICollectionView = {
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: 50 , height: 50)
        flowLayout.sectionInset = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        collectionView.backgroundColor = UIColor.black
        
        return collectionView
    }()

UICollectionViewCell 타입의 ButtonCell class를 생성해 준다.

//
//  ButtonCell.swift
//  CoupangClon
//
//  Created by SeoJunYoung on 2023/02/10.
//

import UIKit

final class ButtonCell: UICollectionViewCell {
    

        //var buttonColor =
        let contantView: UIView = {
            let contantView = UIView()
            contantView.translatesAutoresizingMaskIntoConstraints = false
            contantView.heightAnchor.constraint(equalToConstant: 80).isActive = true
            contantView.widthAnchor.constraint(equalToConstant: 80).isActive = true
            contantView.backgroundColor = UIColor.white
            return contantView
        }()
        let button:UIButton = {
            let button = UIButton()
            button.translatesAutoresizingMaskIntoConstraints = false
            button.setTitleColor(UIColor.black, for: .normal)
            button.titleLabel?.font = UIFont.systemFont(ofSize: 45)
            button.contentHorizontalAlignment = .center
            return button
        }()
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            self.addSubview(contantView)
            setConstraints()
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        
        override func updateConstraints() {
            setConstraints()
            super.updateConstraints()
            
        }
        
        func setConstraints(){
            contantView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
            contantView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
            setButtonUI()
        }
        
        func setButtonUI(){
            contantView.addSubview(button)
            NSLayoutConstraint.activate([
                button.centerXAnchor.constraint(equalTo: contantView.centerXAnchor),
                button.centerYAnchor.constraint(equalTo: contantView.centerYAnchor)
                
            ])
            contantView.layer.cornerRadius = 40
            
        }
    
    
    
    
    
}

dataSource와 delegate를 self로 할당해 주고 Cell을 등록한다.

func slideViewUI(){
        contentView.addSubview(slideView)
        slideView.dataSource = self
        slideView.delegate = self
        slideView.register(ButtonCell.self, forCellWithReuseIdentifier: "ButtonCell")
    }

ViewController를 확장하여 필수 메서드 2개를 생성한다.

extension ViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView,
            layout collectionViewLayout: UICollectionViewLayout,
            sizeForItemAt indexPath: IndexPath) -> CGSize {

                let interval:CGFloat = 5
                let width: CGFloat = ( UIScreen.main.bounds.width - interval * 2 ) / 5
                return CGSize(width: width , height: width + 30) //Cell의 크기 지정
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return buttonTitle.count //Cell의 갯수 필수
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if collectionView == slideView{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ButtonCell", for: indexPath) as! ButtonCell
            cell.button.setTitle(buttonTitle[indexPath.row], for: .normal)
            var myColor = ["-","+","/","*","="].contains(buttonTitle[indexPath.row]) ? UIColor.yellow : UIColor.gray
            cell.contantView.backgroundColor = myColor
            cell.button.setTitleColor(UIColor.black, for: .normal)
            return cell //Cell의 등록 필수
        }
        return UICollectionViewCell()
    }
    
}