我发现了一些奇怪的东西。我创建了一个自定义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
并选择您的CollectionView
。现在打开“大小检查器”,并将估计的大小 Automatic
更改为None
。
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS82OGlkTi5wbmcifQ==” alt =“在此处输入图像描述”>“ >>
希望这会起作用。
您可以使用UICollectionViewFlowLayout()
设置单元格的大小