UICollectionViewCell is wrong width with label [duplicate]

杀马特。学长 韩版系。学妹 提交于 2020-03-22 12:43:31

问题


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.

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.

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

Then, collectionViewCell width is broke.

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

}

回答1:


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

Hope this will work.




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/60755978/uicollectionviewcell-is-wrong-width-with-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!