【问题标题】:Improper width of cell in collectionview集合视图中单元格的宽度不正确
【发布时间】:2020-10-26 10:28:43
【问题描述】:

[更新] 我创建了包含具有不同标题和不同宽度的单元格的集合视图。当我在启动应用程序时阅读集合时,它工作正常。 但是当我在使用应用程序期间添加新单元格时,它具有标准、窄、宽度。 当我再次重新启动应用程序时,它将再次具有正确的宽度。

添加 reloadData() 后,它适用于一个单元格。但是当我有多个单元格时,它们会相互绘制。

这里是代码:

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.reloaddata()后重新加载collectionview@
  • 谢谢!就是这样。它现在工作正常。 :)
  • 欢迎,别忘了给答案点赞:)
  • 但是,当我在 collectionview 中有多个单元格时,它们会一个一个地绘制在另一个单元格上 :( 现在。
  • 能不能加代码和截图

标签: swift xcode


【解决方案1】:

试试看:-

添加元素后重新调用collectionview。

collectionview.reloaddata()

[编辑]

  • 将流布局添加到集合视图
  • 添加以下代码

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

更多信息请访问https://stackoverflow.com/a/53284536/12451658

【讨论】:

  • 再次感谢。它工作得很好。你为我节省了很多时间:D