Home > Blockchain >  Dynamic UICollectionView -> errors and visual layout problems
Dynamic UICollectionView -> errors and visual layout problems

Time:05-10

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

CodePudding user response:

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

  • Related