Search code examples
iosswiftuicollectionviewautolayoutuicollectionviewcell

UICollectionViewCell is wrong width with label


I found something strange.
I created a custom UICollectionViewCell and a label inside it.
I applied auto-layout only to the top, leading, and bottom of the label.

enter image description here

class TestCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var label: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
    }
}

And if the text is long, it is clipped off the screen like below.

enter image description here

I want the text to be displayed as just "..." if it is too long.
So I applied traling auto-layout like this.

enter image description here

Then, collectionViewCell width is broke.

enter image description here

This is my code.
I already set delegate, datasource.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? TestCollectionViewCell else { return UICollectionViewCell() }
        cell.label.text = "asdfasdkfjabsdkljfbasdfhaoweihf;oaisefowiejfao;wihfaksdjfhakdjf;lskdjfa;zxknb"
        return cell
    }

}

extension ViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (collectionView.frame.width - 1) / 2, height: 53)
    }

}

Solution

  • Open Storyboard and select your CollectionView.
    Now open Size inspector and change Estimated size Automatic to None.

    enter image description here

    Hope this will work.