1

I have a UICollectionView. How can I set the cell width = label width programmatically

I have implemented UICollectionViewDelegateFlowLayout and UICollectionViewDataSource.

 let musicType = ["Blues", "Klasik Müzik", "Halk Müzikleri", "Hip-hop", "Caz", "Pop", "Rock", " Enstrümantal Müzik", "House", "Rap" , "Slow"]

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return musicType.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath as IndexPath) as! CustomCell
        cell.nameLabel.text = musicType[indexPath.item]
        cell.sizeToFit()
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        ?????
    }



}

class CustomCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    let nameLabel: UILabel = {
       let lbl = UILabel()
        lbl.text = "deneme Tag"
        lbl.translatesAutoresizingMaskIntoConstraints = false
        return lbl
    }()


    func setupView(){
        backgroundColor = UIColor.red
        addSubview(nameLabel)
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-10-[v0]-10-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
    }

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




}

1 Answer 1

1

You need to get the attributes for the label then create an NSAttributedString with the data for the give index path. NSAttributedString has a size method which will tell you how big the text should be.

It looks like your label has no attributes and no data so assuming you want the cell to be the actual size of your label with zero padding its:

let text = NSAttributedString(string: "deneme Tag")
return text.size()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.