MVC로 코드를 작성할 때 ViewController의 코드를 줄일려고
CollectionView를 다른 파일로 분리시켰습니당
갑자기 velog에 작성해두고 싶어서 적어보기,,
Swift5로 작성했구여 사용한 라이브러리는 없습니다
일단 파일은
class MainViewController: BaseViewController {
private let collectionView = CardCollecionView(collectionViewLayout: UICollectionViewFlowLayout.init())
...
override func setup() {
guard let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
layout.itemSize = CGSize(width: view.frame.width - 48, height: 240)
layout.minimumLineSpacing = linespacing //변수 설정해주세유
layout.scrollDirection = .horizontal
collectionView.view.frame = self.view.frame
}
override func layout() {
view.addSubview(collectionView.view)
self.addChild(collectionView)
collectionView.view.translatesAutoresizingMaskIntoConstraints = false
}
}
그리고 collectionView.view의 layout을 설정해줍니다
class CardCollecionView: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
}
...
extension CardCollecionView {
private func setup() {
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.collectionView.register(CardCell.self, forCellWithReuseIdentifier: "CardCell")
self.collectionView.backgroundColor = .clear
self.collectionView.showsHorizontalScrollIndicator = false
self.collectionView.contentInset = UIEdgeInsets(top: 0, left: 24, bottom: 0, right: 24)
self.collectionView.decelerationRate = UIScrollView.DecelerationRate.fast
}
}
extension CardCollecionView {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cardList.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CardCell", for: indexPath) as? CardCell else { return UICollectionViewCell() }
cell.titleLabel.text = cardList[indexPath.row].title
cell.numberLabel.text = cardList[indexPath.row].cardNumber
return cell
}
}
class CardCell: UICollectionViewCell {
let titleLabel: UILabel = {
$0.textColor = .black
return $0
}(UILabel())
let numberLabel: UILabel = {
$0.textColor = .black
return $0
}(UILabel())
override init(frame: CGRect) {
super.init(frame: frame)
setup()
layout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CardCell {
private func setup() {
}
private func layout() {
}
}
최대한 간단하게 함 적어봤습니다
저는 이런식으로 해서 collectionView를 나눠봤어요!
재밌어요🌊