Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add cells in UICollectionView from bottom to top using Swift 4.2

I'm trying to implement a Chat screen using UICollectionView in Swift 4.2. I've done it. I want to improve it by making the cells grow from bottom to top instead of top to bottom (while keeping the order of messages too). Any help? I've tried searching for it, still unsuccessful.

enter image description here

like image 601
Mumtaz Hussain Avatar asked Oct 15 '25 03:10

Mumtaz Hussain


2 Answers

The easiest way would be to flip the collection view and its cells:-

cv.transform = CGAffineTransform(scaleX: 1, y: -1)
cell.contentView.transform = CGAffineTransform(scaleX: 1, y: -1)

Doing this will just flip your CollectionView's content and won't require you to handle anything, I guess

EDIT:-

For your requirement, you shouldn't be appending elements to your array. You should insert new objects as the first element of the array(the data source):-

myArray.insert(element, at: 0)

In order to get the right order, you can just reverse the array

like image 66
Lokesh SN Avatar answered Oct 17 '25 19:10

Lokesh SN


You can modify the top inset of the collection view as the collectionView reloads.

Call this after calling reloadData():

func updateCollectionContentInset() {
    let contentSize = yourCollectionView.collectionViewLayout.collectionViewContentSize
    var contentInsetTop = yourCollectionView.bounds.size.height

        contentInsetTop -= contentSize.height
        if contentInsetTop <= 0 {
            contentInsetTop = 0
    }
    yourCollectionView.contentInset = UIEdgeInsets(top: contentInsetTop,left: 0,bottom: 0,right: 0)
}
like image 40
Kristian H Avatar answered Oct 17 '25 18:10

Kristian H