iOS/iOS Swift 개발 일기

iOS swift) collectionview with snapkit

Developer-Michelle 2022. 9. 11. 22:58

iOS swift) collectionview with snapkit

연습이 많이 필요한 지점...

인스타그램 사진 뜨듯이 위에처럼 만들어보려고 할 때 아래와 같이 해보았다.

 

Launching App 프로젝트 중

PhotoViewController.swift

 

override func loadView() { 

        self.view = mainView

    }

 override func viewDidLoad() {

        super.viewDidLoad()

 

//MARK: -collectionView 등록

        mainView.collectionView.backgroundColor = Constants.BaseColor.background

        

        mainView.collectionView.snp.makeConstraints { make in

            make.edges.equalTo(view.safeAreaLayoutGuide).inset(UIEdgeInsets(top: 120, left: 0, bottom: 0, right: 0))

        //표시해 주어야 하는 라벨이 위에 있어서 위에부분을 120만큼 띄운것임

        

        mainView.collectionView.delegate = self

        mainView.collectionView.dataSource = self

        mainView.collectionView.register(PhotoCollectionViewCell.self, forCellWithReuseIdentifier: "PhotoCollectionViewCell")

 

//MARK: - collectionview + extension

extension PhotoViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 20 (test로 해보았음)

    }

    

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCollectionViewCell", for: indexPath) as? PhotoCollectionViewCell else {

            return UICollectionViewCell()

        }

        cell.backgroundColor = Constants.BaseColor.background

        cell.thingImg.image = UIImage(named: "camera") (테스트 사진)

        return cell

    }

}

 

PhotoView.swift

class PhotoView: BaseView {

//MARK: - collectionview (사진 목록)

    let collectionView: UICollectionView = {

        let view = UICollectionView(frame: .zero, collectionViewLayout: imageCollectionViewLayout())

        return view

    }()

 

override init(frame: CGRect) {

        super.init(frame: frame)

    }

    

    required init?(coder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    

    override func configureUI() {

        [infoLabel, collectionView].forEach {

            self.addSubview($0)

        }

    }

 

static func imageCollectionViewLayout() -> UICollectionViewFlowLayout {

        let layout = UICollectionViewFlowLayout()

        layout.minimumLineSpacing = //행과 행 사이의 간격

        layout.minimumInteritemSpacing = 6 //열과 열 사이의 간격

        let itemSpacing : CGFloat = 6 //열과 열 사이의 간격을 하나의 변수로 정의해서 밑에 너비를 구할 때 이용함

        let myWidth : CGFloat = (UIScreen.main.bounds.width - itemSpacing * 2) / //컬렉션 뷰 3열로 등록하고 싶은 경우, 전체 너비에서 열과 열 사이의 간격은 2개가 있고, 먼저 이 간격의 총합을 뺀 뒤, 그 길이에서 3으로 나눠주면 3등분 되어 이미지가 들어가게 됨.

        layout.itemSize = CGSize(width: myWidth, height: myWidth) //너비와 높이를 같게 하고 싶은 경우

        return layout

    }

}

 

PhotoCollectionViewCell.swift

class PhotoCollectionViewCell: UICollectionViewCell {

    //MARK: - imageView

    lazy var thingImg: UIImageView = {

        let view = UIImageView()

        return view

    }()

    

    override init(frame: CGRect) {

        super.init(frame: frame)

        self.cellSetting()

    }

    

    required init?(coder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }

    

    func cellSetting() {

        self.backgroundColor = Constants.BaseColor.background

        [thingImg].forEach {

            self.contentView.addSubview($0)

        }

        thingImg.contentMode = .scaleToFill

        thingImg.snp.makeConstraints { make in

            make.edges.equalToSuperview() // 이렇게 하는게 핵심이었음. 자꾸 너비, 높이 고정값을 주면 아무리 컬렉션뷰 다른 속성들을 바꾸더라도 바꿔지지가 않았다.

//            make.width.equalTo(100)

//            make.height.equalTo(100)

        }

    }

}

 

 

https://rldd.tistory.com/195

 

iOS Snapkit 09 | CollectionView 코드로 구성하는 법 02

✅ 이번에는 이전 포스팅은 기본 셀을 사용했다면 커스텀 셀을 사용하는 방법에 대해서 알아볼 예정이야. // // File.swift // SnapKit_practice // // Created by Hamlit Jason on 2021/08/22. // import UIKit i..

rldd.tistory.com