UICollectionViewCell的标签宽度错误 [英] UICollectionViewCell is wrong width with label

查看:221
本文介绍了UICollectionViewCell的标签宽度错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些奇怪的东西.
我创建了一个自定义UICollectionViewCell及其内部的标签.
我仅将自动布局应用于标签的顶部,顶部和底部.

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.

然后,collectionViewCell的宽度被破坏了.

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

}

推荐答案

打开Storyboard并选择您的CollectionView.
现在打开大小"检查器,然后将估计的大小 Automatic更改为None.

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

希望这会起作用.

这篇关于UICollectionViewCell的标签宽度错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆