0

I am trying to create a collection view with dynamic width of CollectionView Cell. But In my case, cells are coming scattered. I need to make it all aligned on left. Here is my code:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let text = usersHashArray[indexPath.row]["name"] as! String
    var width = self.estimatedFrame(text: text, font: UIFont(name:Fonts.SFProText_Regular, size: 14)!, height: 20).width
    return CGSize(width: width, height: 38)
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UsersHashCollectionViewCell", for: indexPath) as! UsersHashCollectionViewCell
    let dict = usersHashArray[indexPath.row]
    cell.userNameLabel.text! = dict["name"] as! String

    if checkForHashTag(text: dict["name"] as! String) == true {
        cell.userImageWidthConstraint.constant = 0
    }
    else {
        cell.userImageWidthConstraint.constant = 28
    }
                
    cell.crossButton.addTarget(self, action: #selector(removeUserFromHashList), for: .touchUpInside)
    cell.crossButton.tag = indexPath.row
    return cell
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}


Here is the image, how it is coming right now: Scattered collectionview cells

How can I fix the alignment issue?

Gautam Shrivastav
  • 918
  • 1
  • 8
  • 21

0 Answers0