본문 바로가기
UIKIT

UICollectionView의 셀 크기를 동적으로 정사각형으로 조정하려면?

by 밤새는 탐험가89 2024. 12. 22.
728x90
SMALL

UICollectionViewDelegateFlowLayout의 sizeForItemAt 메서드를 구현해야 합니다. 또한 UICollectionView의 레이아웃을 적절히 구성하여, 셀의 너비와 높이를 동일하게 설정하도록 보장해야 합니다.

 

1. ImagePickerCell에서 UICollectionViewDelegateFlowLayout 채택

ImagePickerCell 클래스에서 UICollectionViewDelegateFlowLayout를 채택하고, sizeForItemAt을 구현합니다.

extension ImagePickerCell: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // 셀 크기를 동적으로 계산하여 정사각형으로 만듦
        let height = collectionView.frame.height
        let size = CGSize(width: height, height: height)
        return size
    }
}

 

2. collectionView의 높이를 부모 레이아웃에 맞게 조정

imageCollelcitonView의 높이가 UICollectionViewFlowLayout의 itemSize에서 지정한 크기에 맞도록 설정되어야 합니다. 기본적으로 imageCollelcitonView의 높이는 부모 뷰의 제약 조건으로부터 영향을 받으므로, 이를 명시적으로 지정해야 합니다.

아래와 같이 imageCollelcitonView에 적절한 높이를 부여합니다:

NSLayoutConstraint.activate([
    // Other constraints
    imageCollelcitonView.leadingAnchor.constraint(equalTo: imageButton.trailingAnchor, constant: 10),
    imageCollelcitonView.topAnchor.constraint(equalTo: imageButton.topAnchor),
    imageCollelcitonView.bottomAnchor.constraint(equalTo: basicView.bottomAnchor, constant: -5),
    imageCollelcitonView.trailingAnchor.constraint(equalTo: basicView.trailingAnchor, constant: -5),
    
    // 고정된 높이를 사용하지 않음: 기본 높이는 동적으로 변경 가능
    imageCollelcitonView.heightAnchor.constraint(equalToConstant: 100) // 필요에 따라 조정
])

 

 

3. 최종 코드

import UIKit

class ImagePickerCell: UITableViewCell{
    
    // MARK: - Variables
    static var reuseIdentifier: String = "ImagePickerCell"
    
    var selectedImageArray: [String] = ["Museum", "Nature"] {
        didSet {
            // 데이터가 변경될 때 컬렉션뷰를 업데이트
            imageCollelcitonView.reloadData()
        }
    }
    
    // MAKR: - UI Componnets
    private let basicView: UIView = {
        let view = UIView()
        view.backgroundColor = .secondarySystemBackground
        view.layer.cornerRadius = 10
        view.clipsToBounds = true
        return view
    }()
    
    private let imageTitle: CustomLabel = CustomLabel(customLabelType: .title, title: "사진을 선택해주세요")
    
    private let imageButton: CustomButton = CustomButton(customButtonType: .systemName(imageName: "camera", title: "최대 5장 선택 가능"), hasBackground: true)
    
    private let imageCollelcitonView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumInteritemSpacing = 15
        //layout.itemSize = CGSize(width: 100, height: 100)
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .clear
        return collectionView
    }()
    
    // MARK: - Life Cycle
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        contentView.backgroundColor = .systemBrown
        
        configureConstraints()
        setupDelegate()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Layouts
    private func configureConstraints() {
        contentView.addSubview(basicView)
        
        basicView.addSubview(imageTitle)
        basicView.addSubview(imageButton)
        basicView.addSubview(imageCollelcitonView)
        
        basicView.translatesAutoresizingMaskIntoConstraints = false
        imageTitle.translatesAutoresizingMaskIntoConstraints = false
        imageButton.translatesAutoresizingMaskIntoConstraints = false
        imageCollelcitonView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            
            basicView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            basicView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            basicView.topAnchor.constraint(equalTo: contentView.topAnchor),
            basicView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
            
            imageTitle.leadingAnchor.constraint(equalTo: basicView.leadingAnchor, constant: 5),
            imageTitle.topAnchor.constraint(equalTo: basicView.topAnchor, constant: 5),
            
            imageButton.leadingAnchor.constraint(equalTo: basicView.leadingAnchor, constant: 5),
            imageButton.centerYAnchor.constraint(equalTo: basicView.centerYAnchor, constant: 5),
            imageButton.widthAnchor.constraint(equalToConstant: 80),
            imageButton.heightAnchor.constraint(equalToConstant: 80),
            
            imageCollelcitonView.leadingAnchor.constraint(equalTo: imageButton.trailingAnchor, constant: 10),
            imageCollelcitonView.topAnchor.constraint(equalTo: imageTitle.bottomAnchor, constant: 5),
            imageCollelcitonView.bottomAnchor.constraint(equalTo: basicView.bottomAnchor, constant: -5),
            imageCollelcitonView.trailingAnchor.constraint(equalTo: basicView.trailingAnchor, constant: -5),
            
            // 고정된 높이를 사용하지 않음: 기본 높이는 동적으로 변경 가능
            imageCollelcitonView.heightAnchor.constraint(equalToConstant: 150) // 필요에 따라 조정
            
        ])
        
    }
    
    // MARK: - Functions
    private func setupDelegate() {
        imageCollelcitonView.delegate = self
        imageCollelcitonView.dataSource = self
        imageCollelcitonView.register(ImageCell.self, forCellWithReuseIdentifier: ImageCell.resumeIdentifier)
    }
    
}

// MARK: - Extension
extension ImagePickerCell: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return selectedImageArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let image = selectedImageArray[indexPath.row]
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageCell.resumeIdentifier, for: indexPath) as? ImageCell
        
        cell?.configure(with: image)
        
        return cell!
    }
    
}

extension ImagePickerCell: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // 셀 크기를 동적으로 계산하여 정사각형으로 만듦
        let height = collectionView.frame.height
        let size = CGSize(width: height, height: height)
        return size
    }
}
728x90
LIST

'UIKIT' 카테고리의 다른 글

UIFontMetrics  (0) 2025.01.05
키보드 내리기  (0) 2024.12.27
탭바뷰컨트롤러에서 액션시트 나오게 하는 방법  (0) 2024.12.20
델리게이트 패턴으로 사진 선택하기  (0) 2024.12.20
UIScreen과 UIScene  (0) 2024.12.19