UICollectionViewCell 的标签宽度错误

odd*_*ddK 1 ios autolayout uicollectionview uicollectionviewcell swift

我发现了一些奇怪的东西。
我创建了一个自定义 UICollectionViewCell 并在其中创建了一个标签。
我只对标签的顶部、前导和底部应用了自动布局。

在此处输入图片说明

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

    override func awakeFromNib() {
        super.awakeFromNib()
    }
}
Run Code Online (Sandbox Code Playgroud)

如果文本很长,它会像下面一样从屏幕上剪下来。

在此处输入图片说明

如果文本太长,我希望文本仅显示为“...”。
所以我像这样应用了traling自动布局。

在此处输入图片说明

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

在此处输入图片说明

这是我的代码。
我已经设置了委托,数据源。

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

}
Run Code Online (Sandbox Code Playgroud)

Fay*_*med 5

打开Storyboard并选择您的CollectionView.
现在打开尺寸检查器并将估计尺寸 更改AutomaticNone

在此处输入图片说明

希望这会奏效。