[UIKit] UICollectionView: Custom Circular Cell

Junyoung Park·2022년 10월 29일
0

UIKit

목록 보기
63/142
post-thumbnail
post-custom-banner

Swift Collection View Like Instagram Stories (Xcode 11, Swift 5)

UICollectionView: Custom Circular Cell

구현 목표

  • 인스타그램의 스토리와 같은 둥근 모양의 컬렉션 뷰 구현

구현 태스크

  • 커스텀 셀 내의 이미지 뷰 구현
  • 셀 재사용을 위한 오버라이드 함수

핵심 코드

import UIKit

class CircleCollectionViewCell: UICollectionViewCell {
    static let identifier = "CircleCollectionViewCell"
    private let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.layer.masksToBounds = true
        imageView.layer.cornerRadius = 150.0 / 2.0
        imageView.layer.borderWidth = 2.0
        imageView.layer.borderColor = UIColor.systemGray.cgColor
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        imageView.image = nil
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        imageView.frame = contentView.bounds
    }
    
    private func setUI() {
        contentView.addSubview(imageView)
    }
    
    func configure(with name: String) {
        imageView.image = UIImage(named: name)
    }
}
  • clipsToBounds, masksToBounds 등 이미지 뷰 내의 적절한 프로퍼티 값 설정을 통해 레이어에 알맞게 뷰 조정 가능

소스 코드

import UIKit

class CollectionViewController: UIViewController {
    private let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.itemSize = CGSize(width: 150, height: 150)
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.register(CircleCollectionViewCell.self, forCellWithReuseIdentifier: CircleCollectionViewCell.identifier)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .systemPink
        return collectionView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        collectionView.frame = CGRect(x: 0, y: 100, width: view.frame.size.width, height: 150).integral
    }
    
    private func setUI() {
        view.backgroundColor = .systemBackground
        view.addSubview(collectionView)
        collectionView.delegate = self
        collectionView.dataSource = self
    }
}

extension CollectionViewController: UICollectionViewDelegate {
    
}

extension CollectionViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CircleCollectionViewCell.identifier, for: indexPath) as? CircleCollectionViewCell else {
            return UICollectionViewCell()
        }
        if let number = (1...10).randomElement() {
            let imageName = "cat_\(number)"
            cell.configure(with: imageName)
        }
        return cell
    }
}

extension CollectionViewController: UICollectionViewDelegateFlowLayout {
}
  • 커스텀 컬렉션 뷰 구현
  • 10개의 셀 아이템 내에 랜덤 이미지로 바인딩
import UIKit

class CircleCollectionViewCell: UICollectionViewCell {
    static let identifier = "CircleCollectionViewCell"
    private let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.clipsToBounds = true
        imageView.contentMode = .scaleAspectFill
        imageView.layer.masksToBounds = true
        imageView.layer.cornerRadius = 150.0 / 2.0
        imageView.layer.borderWidth = 2.0
        imageView.layer.borderColor = UIColor.systemGray.cgColor
        return imageView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        imageView.image = nil
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        imageView.frame = contentView.bounds
    }
    
    private func setUI() {
        contentView.addSubview(imageView)
    }
    
    func configure(with name: String) {
        imageView.image = UIImage(named: name)
    }
}
  • 커스텀 컬렉션 셀

구현 화면

profile
JUST DO IT
post-custom-banner

0개의 댓글