简体   繁体   中英

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.

在此处输入图片说明

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

You have to make collection view height constraint outlet for it and calculate your cells height after that you can set height of collectionView. and one case will come of maximum height, your collection height will equal from screen height with calculate space your navigation and input textview.

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

Have you tried

let diff = collectionView.frame.height - collectionView.contentSize.height
if diff > 0 {
    collectionView.contentInset = UIEdgeInsets(top: diff, left: 0, bottom: 0, right: 0)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM