UICollectionViewCell is wrong width with label

Viewed 615

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)
    }

}
3 Answers

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.

Try calculating size of cell as:

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

You can set the size of the cell using UICollectionViewFlowLayout()

In your viewDidLoad

override func viewDidLoad() {
    collectionView.dataSource = self

    let layout = UICollectionViewFlowLayout()
    layout.itemSize = CGSize(width: (collectionView.frame.width - 1) / 2, height: 53)
    collectionView.setCollectionViewLayout(layout, animated: true)
}

Discription

Related