UICollectionViewCell的标签宽度错误

问题描述 投票:0回答:2

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

enter image description here

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

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

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

enter image description here

如果文本太长,我希望文本显示为“ ...”。因此,我像这样应用了调整自动布局。

enter image description here

然后,collectionViewCell的宽度被破坏。

enter image description here

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

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

}
ios swift uicollectionview autolayout uicollectionviewcell
2个回答
1
投票

尝试将像元的大小计算为:

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

0
投票

打开Storyboard并选择您的CollectionView。现在打开“大小检查器”,并将估计的大小 Automatic更改为None

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS82OGlkTi5wbmcifQ==” alt =“在此处输入图像描述”>“ >>

希望这会起作用。


0
投票

您可以使用UICollectionViewFlowLayout()设置单元格的大小

© www.soinside.com 2019 - 2024. All rights reserved.