This is the view I want to replicate:
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):
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...
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
}