iOS/ios 아무거나 만들어보기

CollectionView UICollectionViewDelegate 사용해보기

728x90

- 다른 기능은 뭐가 있지?

  • 단일 Cell 선택 하기.
  • 다중 Cell 선택을 구현합니다.
  • Cell을 드래그하기 쉽게 이동할 수 있습니다.

 

단일 Cell 선택하기

 

생성한 Color들을 선택하면 Check 표시가 나게 설정해보자.

Color를 선택하면 체크가 된 원으로 바꾸기 위해 Asset에 svg 이미지를 추가했다.

color Pick

 

ColorViewCell로 들어가 Cell에서 ImageView를 생성해준다.

이 ImageView를 통해 Color가 선택되었다면, color_pick이미지를 불러 올 것이다.

class ColorViewCell: UICollectionViewCell {
    // MARK: - Properties
    
    var colorView: UIImageView = {
       let iv = UIImageView()
        iv.clipsToBounds = true
        return iv
    }()
    
 }

 

UICollectionViewCell에서 isSelected라는  속성을 사용해 Cell이 선택 되었는지 확인 할 수 잇다.

isSelected값이 변경 될 때마다 colorview를 업데이트 시켜야 되기때문에 isSelected를 override해준다.

class ColorViewCell: UICollectionViewCell {
   override var isSelected: Bool {
        didSet {
            // configureUI()
        }
    }
 }

 

 

configureUI 메서드에 아래와 같이 추가해주자.

 // ColorCode가 변경되면, Cell의 background 색을 변경함
    func configureUI() {
        guard let colorCode = colorCode else {
            return
        }
      
        // 선택한 경우
        if isSelected {
            colorView.image = UIImage(named: "color_pick")?.withRenderingMode(.alwaysTemplate)
            colorView.tintColor = UIColor(rgb: colorCode)
            colorView.backgroundColor = .white
        }
        // 선택하지 않은 경우
        else {
            colorView.tintColor = .clear
            colorView.backgroundColor = UIColor(rgb: colorCode)
        }
    }

 

원리는 ColorView가 선택되었다면, 체크 표시 이미지를 불러와주고 이미지의 색깔을 colorCode(Color Hex Code)에게서 전달 받은 값으로 바꿔주면 된다. 

반대로 선택되지 않았다면 체크 표시 이미지의 색을 투명하게 바꿔주고, 뒷 배경을을 colorCode색으로 바꿔준다.

 

기본 선택 위치 설정

처음 어떤 cell을 선택 할 지 지정 할 수가 있다.

ColorViewController에서 아래와 같이 viewDidAppear을 추가해줍니다.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    // 기본 선택 위치 설정
    let selectedIndexPath = IndexPath(row: 0, section: 0)
    collectionView.selectItem(at: selectedIndexPath, animated: true, scrollPosition: .left)
}

 

여러개 선택하기 

ColorViewController viewDidLoad에서 allowMulitpleSelection을 true로 변경 해줍니다.

 override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.register(ColorViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        // 여러개 선택하기
        collectionView.allowsMultipleSelection = true
    }

 

 

전체 소스

 

GitHub - HOONITANG/CollectionViewExample

Contribute to HOONITANG/CollectionViewExample development by creating an account on GitHub.

github.com

//
//  ColorViewCell.swift
//  CollectionViewExample
//
//  Created by Taehoon Kim on 2022/02/16.
//

import UIKit

class ColorViewCell: UICollectionViewCell {
    // MARK: - Properties
    
    var colorView: UIImageView = {
       let iv = UIImageView()
        iv.clipsToBounds = true
        return iv
    }()
    
    // Controller에게서 전달 받을 colorCode
    var colorCode: Int? {
        didSet {
            configureUI()
        }
    }
    
    // MARK: - Lifecycle
    override init(frame: CGRect) {
        super.init(frame: frame)
        colorView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
        colorView.layer.cornerRadius = frame.width / 2
        addSubview(colorView)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // Helper
    override var isSelected: Bool {
        didSet {
            configureUI()
        }
    }
    
    // ColorCode가 변경되면, Cell의 background 색을 변경함
    func configureUI() {
        guard let colorCode = colorCode else {
            return
        }
      
        // 선택한 경우
        if isSelected {
            colorView.image = UIImage(named: "color_pick")?.withRenderingMode(.alwaysTemplate)
            colorView.tintColor = UIColor(rgb: colorCode)
            colorView.backgroundColor = .white
        }
        // 선택하지 않은 경우
        else {
            colorView.tintColor = .clear
            colorView.backgroundColor = UIColor(rgb: colorCode)
        }
    }
}
//
//  ViewController.swift
//  CollectionViewExample
//
//  Created by Taehoon Kim on 2022/02/16.
//

import UIKit

private let reuseIdentifier = "ColorViewCell"

class ColorViewController: UICollectionViewController {
    
    /// 보여줄 데이터
    let colorHexCodes = [0x000000,0xff3b30,0x007aff,0xff9500,0x4cd964,
                         0xEDCFA9,0xE89F72,0xFF935E,0xD5724A,0xAA4B31,
                         0xFCD1D1,0xECE2E,0xD3E0DC,0xAEE1E1,0xD9D7F1,
                         0x93B5C6,0xBCEBFD,0xC9CCD5,0xE4D8DC,0xFFE3E3,
                         0x535353,0x424242,0x323232,0x06405FA,0x032D44,
                         0xFEFFDE,0xDDFFBC,0x91C788,0x53744E,0x5D272D,
                         0x493535,0x6C5050,0xEED6C4,0xFFF3E4,0xFCF0C8,
                         0xC6D57F,0xD57F7F,0xA2CDCD,0xF4DFB3,0x3E2257]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.register(ColorViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        // 여러개 선택하기
        collectionView.allowsMultipleSelection = true
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 기본 선택 위치 설정
        let selectedIndexPath = IndexPath(row: 0, section: 0)
        collectionView.selectItem(at: selectedIndexPath, animated: true, scrollPosition: .left)
    }
}


// MARK: UICollectionViewDataSource
extension ColorViewController {
    
    /// cell 데이터가 몇 개인가
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return colorHexCodes.count
    }
    
    /// 각 Cell에 필요한 데이터를 설정한다.
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ColorViewCell
        
        cell.colorCode = colorHexCodes[indexPath.row]
        
        return cell
    }
}

// MARK: UICollectionViewDelegate
extension ColorViewController {
    
    /// cell 데이터가 몇 개인가
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
}

// MARK: - UIColor
/// Hex Code Color을 사용하게 하는 함수
// let color = UIColor(rgb: 0xFFFFFF)
// let color = UIColor(rgb: 0xFFFFFF).withAlphaComponent(1.0)
// let color2 = UIColor(argb: 0xFFFFFFFF)
extension UIColor {
    convenience init(red: Int, green: Int, blue: Int, a: Int = 0xFF) {
        self.init(
            red: CGFloat(red) / 255.0,
            green: CGFloat(green) / 255.0,
            blue: CGFloat(blue) / 255.0,
            alpha: CGFloat(a) / 255.0
        )
    }
    
    convenience init(rgb: Int) {
        self.init(
            red:(rgb >> 16) & 0xFF,
            green:(rgb >> 8) & 0xFF,
            blue: rgb & 0xFF
        )
    }
    
    // let's suppose alpha is the first component (ARGB)
    
    convenience init(argb: Int) {
        self.init(
            red: (argb >> 16) & 0xFF,
            green: (argb >> 8) & 0xFF,
            blue: argb & 0xFF,
            a: (argb >> 24) & 0xFF
        )
    }
}

 

실행화면

실행 화면

반응형