【问题标题】:UICollectionViewCell is wrong width with label [duplicate]UICollectionViewCell 的标签宽度错误[重复]
【发布时间】:2020-06-30 12:24:56
【问题描述】:

我发现了一些奇怪的东西。
我在其中创建了一个自定义 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)
    }

}

【问题讨论】:

标签: ios swift uicollectionview autolayout uicollectionviewcell


【解决方案1】:

您可以使用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)
}

【讨论】:

    【解决方案2】:

    打开Storyboard 并选择您的CollectionView
    现在打开 Size inspector 并将 Estimated size Automatic 更改为 None

    希望这会奏效。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 不,我的代码结果完全相同。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 2012-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多