1

[updated] I have created collectionview containing cells with different captions and different widths. It works fine when I read collection on launch of application. But when I add new cell during usage of the application it has standard, narrow, width. When I again relaunch the application it will again have correct width.

After adding reloadData() it works fine for one cell. But when I have multiple cells they are drawn one on each other. enter image description here

And here is the code:

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
}

When I remove the row: cell.projectButton.sizeToFit() it started to look like this: enter image description here

1 Answers1

1

try it :-

relod collectionview after adding element.

collectionview.reloaddata()

[edited]

  • add flowlayout to collectionview
  • add below code

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

for more visit https://stackoverflow.com/a/53284536/12451658

Shivam Parmar
  • 1,520
  • 11
  • 27