Saturday, November 21, 2026
HomeiOS Developmentios - Tips on how to make horizontal CollectionView measurement match its...

ios – Tips on how to make horizontal CollectionView measurement match its content material programatically

[ad_1]

I’ve a set view which takes up the entire display screen and will scroll horizontally.

Downside is I am unable to regulate the scale for merchandise whereas retaining the carousel impact. If I decrease the scale for merchandise, the cell stacks vertically similar to right here:

enter image description here

The pink background is the collectionView. The collectionView fills the viewController’s view that’s the reason the cells would not align horizontally.

The alignment ought to be like this which scrolls horizontally very like a carousel however the issue is it is too massive and it took up the entire view.

enter image description here

What’s anticipated is for the cell and assortment view to be round 100 peak or 200 peak solely and might nonetheless scroll horizontally.

That is my present code:

I’m utilizing SnapKit for constraints.

ViewController

import UIKit
import SnapKit

class ViewController: UIViewController {
    
    
    let viewModel: [SeatViewModel] = [.init(text: "single text"), .init(text: "slightly longer text."), .init(text: "very very very very long long text")]
    
    personal lazy var collectionView: UICollectionView = {
      let structure = UICollectionViewFlowLayout()
        structure.scrollDirection = .horizontal
      let cv = UICollectionView(body: .zero, collectionViewLayout: structure)
      cv.delegate = self
      cv.backgroundColor = .white
      cv.register(SeatCardCell.self, forCellWithReuseIdentifier: "SeatCardCell")
      return cv
    }()


    override func viewDidLoad() {
        tremendous.viewDidLoad()
        view.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { make in
            make.middle.equalToSuperview()
            make.width.equalTo(200)
            make.peak.equalTo(100)
        }
        collectionView.dataSource = self
        collectionView.backgroundColor = .systemPink
    }
    

    
    func traces(label: UILabel) -> Int {
        self.collectionView.layoutIfNeeded()
        let textSize = CGSize(width: label.body.measurement.width, peak: CGFloat(Float.infinity))
        let rHeight = lroundf(Float(label.sizeThatFits(textSize).peak))
        let charSize = lroundf(Float(label.font.lineHeight))
        let lineCount = rHeight/charSize
        return lineCount
    }
    
    override func viewDidLayoutSubviews() {
        tremendous.viewDidLayoutSubviews()
        collectionView.body = view.bounds
    }
    
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection part: Int) -> Int {
        return 3
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let collectioCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SeatCardCell", for: indexPath) as? SeatCardCell else { fatalError() }
        collectioCell.backgroundColor = [UIColor.green, .red, .black, .brown, .yellow].randomElement()
        collectioCell.viewModel = viewModel[indexPath.row]
        return collectioCell
    }
    
}


extension ViewController: UICollectionViewDelegateFlowLayout {
        func collectionView(_ collectionView: UICollectionView,
                            structure collectionViewLayout: UICollectionViewLayout,
                            sizeForItemAt indexPath: IndexPath) -> CGSize {

            return CGSize(width: 200, peak: self.collectionView.body.peak)
        }

        func collectionView(_ collectionView: UICollectionView,
                            structure collectionViewLayout: UICollectionViewLayout,
                            minimumInteritemSpacingForSectionAt part: Int) -> CGFloat {
            return 1.0
        }

        func collectionView(_ collectionView: UICollectionView, structure
            collectionViewLayout: UICollectionViewLayout,
                            minimumLineSpacingForSectionAt part: Int) -> CGFloat {
            return 1.0
        }
    }

View Mannequin and Cell

import UIKit
import SnapKit

struct SeatViewModel {
    let textual content: String
}

class SeatCardCell: UICollectionViewCell {
    
    var viewModel: SeatViewModel? {
        didSet {
            configure()
        }
    }

    // MARK: - Properties

    let seatImageView = UIImageView(picture: nil)
    
    let seatLabel: CustomLabel = {
        let label = CustomLabel()
        return label
    }()

    // MARK: - Lifecycle

    override init(body: CGRect) {
        tremendous.init(body: body)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been applied")
    }

    
    personal func configure() {
        guard let viewModel = viewModel else { return }
        seatLabel.textual content = viewModel.textual content
        seatLabel.backgroundColor = .cyan
        seatLabel.sizeToFit()
        seatImageView.picture = .strokedCheckmark
        
        let stackView = UIStackView(arrangedSubviews: [seatImageView, seatLabel])
        stackView.spacing = 0
        stackView.alignment = .middle
        
        addSubview(stackView)
        
        seatImageView.snp.makeConstraints { make in
            make.measurement.equalTo(40)
        }
        
        stackView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}


// MARK: - CUSTOM TITLE LABEL
class CustomLabel: UILabel {
    
    override init(body: CGRect) {
        tremendous.init(body: body)
        setupUI()
    }
    
    required init(coder: NSCoder) {
        fatalError("init(coder:) has not been applied")
    }
    
    personal func setupUI() {
        self.textColor = .darkGray
        self.textAlignment = .left
        self.numberOfLines = 4
    }
}

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments