Swift collectionview中的单元格宽度不正确
[更新] 我创建了collectionview,其中包含具有不同标题和不同宽度的单元格。当我在应用程序启动时阅读该集合时,它运行良好。 但当我在应用程序使用期间添加新单元格时,它的宽度是标准的、窄的。 当我再次重新启动应用程序时,它将再次具有正确的宽度 在添加reloadData()之后,它对一个单元格工作正常。但当我有多个单元格时,它们是一个一个地画在一起的。 代码如下:Swift collectionview中的单元格宽度不正确,swift,xcode,Swift,Xcode,[更新] 我创建了collectionview,其中包含具有不同标题和不同宽度的单元格。当我在应用程序启动时阅读该集合时,它运行良好。 但当我在应用程序使用期间添加新单元格时,它的宽度是标准的、窄的。 当我再次重新启动应用程序时,它将再次具有正确的宽度 在添加reloadData()之后,它对一个单元格工作正常。但当我有多个单元格时,它们是一个一个地画在一起的。 代码如下: override func viewDidLoad() { super.viewDidLoad()
override func viewDidLoad() {
super.viewDidLoad()
projectCollectionView.delegate = self
projectCollectionView.dataSource = self
projectCollectionView.register(UINib(nibName: "projectCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "projectCollectionViewCell")
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: projectCollectionViewCell.identifier, for: indexPath) as? projectCollectionViewCell
else {
return projectCollectionViewCell()
}
cell.projectButton.setTitle("a title", for: .normal)
projectCollection[indexPath.row].cellIndex = indexPath.row
cell.projectButton.sizeToFit()
cell.layer.bounds.size.width = cell.projectButton.layer.bounds.width
return cell
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
projectCollectionView.collectionViewLayout.invalidateLayout()
projectCollectionView.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var result: Int = 0
for i in 0...projects.count-1 {
if (projects[i].status>=2) {
result += 1
}
}
return result
}
当我删除行:cell.projectButton.sizeToFit()时,它开始如下所示:
试试看:-
添加元素后重新登录collectionview
collectionview.reloaddata()
[已编辑]
- 将flowlayout添加到collectionview
- 添加以下代码
更多信息请访问添加元素后是否重新登录collectionview
collectionview.reloaddata()
谢谢!就这样。现在可以用了欢迎,别忘了向上投票答案:)但是,当我在collectionview中有多个单元格时,它们是一个一个地绘制的:(现在。你能添加代码和屏幕快照吗?再次感谢。它非常有效。你为我节省了很多时间:D
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let label = UILabel(frame: CGRect.zero)
label.text = textArray[indexPath.item]
label.sizeToFit()
return CGSize(width: label.frame.width, height: 32)
}