0

This is the view I want to replicate:

enter image description here

I assume it is a UICollectionView. The width and height should be dynamically calculated based on the content, that is the point I am struggling with.

I created a project where the UICollectionView does not behave like I want: https://github.com/Jasperav/CollectionViewDynamic/blob/master/UIKitTest/ViewController.swift. You can just run the project and see the problem for yourself.

Every time a new Emoji is added, the reloadData method can be called and the UICollectionView size should be equal to the content size but with a maximum width. This is how it looks like when 1 emoji is added (horrible):

enter image description here

It is really weird, the cell is not centered and I get layout errors in the console. When 2 emoji's are added, I would expect the line up next to each other, but they end up beneath each other...

enter image description here

There is enough space for the cells to be next to each other. What am I doing wrong? I calculate the cell's size correctly when I inspect the values in the visual debugger. I think I am doing a lot of manual work to make sure the UICollectionView size is correct, but I don't get it right.

Am I overcomplicating stuff? What I want looks pretty basic to me. This is my first time doing something with the UICollectionView though.

This is how the addEmoji method looks like, the whole code can be seen in the link I mentioned above:

func addEmoji(emoji: Emoji) {
    emojis.append(emoji)

    var width: CGFloat = 0

    for emoji in emojis {
        width += emoji.size().width
    }

    let finalWidth = min(width, 280)

    // Add some breath
    widthAnchor_.constant = finalWidth + 5

    reloadData()

    heightAnchor_.constant = collectionViewLayout.collectionViewContentSize.height
}
NoKey
  • 129
  • 11
  • 32
  • you may looking for somting like this https://stackoverflow.com/questions/22539979/left-align-cells-in-uicollectionview – Abdul Momen May 08 '22 at 11:05

1 Answers1

1

I added small changes to your code and now all works fine (changes is marked with a comment // NEW): https://gist.github.com/sa1dai/b50bec10438b439a8c74cc6e8071bcf4?ts=4

The key idea is not to update heightAnchor_.constant in addEmoji function, but using contentSizeObservation (I took the idea of contentSizeObservation from here).

12357665
  • 36
  • 5