UICollectionViewCell 的标签宽度错误

UICollectionViewCell is wrong width with label

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

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

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

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

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

然后,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)
    }

}

尝试将单元格大小计算为:

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

打开 Storyboard 和 select 您的 CollectionView
现在打开 Size inspector 并将 Estimated size Automatic 更改为 None.

希望这会奏效。

您可以使用 UICollectionViewFlowLayout()

设置单元格的大小

在你的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)
}