我想滚动我的UICollectionView从下到上,当用户点击发送消息UIButton和当用户再次打开应用程序,最后发送的消息必须首先看到底部结束。
我只是尝试了所有的堆栈溢出答案和其他网站的代码,但找不到任何解决方案,我的问题。

import UIKit
import Kingfisher
import Firebase
import IQKeyboardManagerSwift
class FireStoreChatViewController: UIViewController, UITextViewDelegate,UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
@IBOutlet var collectionView: UICollectionView!
@IBOutlet weak var sendMessageBtn: UIButton!
var comeFrom : String = ""
var mChatUser : String = ""
var mChatUserName : String = ""
var mCurruntUserId : String = ""
var isFirstPageFirstLoad: Bool = false
var lastVisible: DocumentSnapshot? = nil
var messageList: [Messages] = []
override func viewDidLoad()
{
super.viewDidLoad()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
self.messageList.reverse()
return messageList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
if messageList[indexPath.row].from == mCurruntUserId
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Message", for: indexPath as IndexPath) as! MessageCollectionViewCell
}
return cell
}
@IBAction func sendMessageAction(_ sender: UIButton)
{
sendMessage()
}
func getMessage(mChatUser: String, mCurruntUser: String)
{
// code
}
func sendMessage()
{
// code
}
func updateChatListData()
{
// code
}
}输出
第一个索引路径第一次看到,而开放聊天应用模块。
发布于 2019-08-09 16:22:45
要让collectionView从底部填充,可以在collectionView重新加载时修改集合视图的顶部嵌入,
在调用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)
}然后,当您希望这样做时,滚动到底部(在数据源的didSet中,在collectionView重新加载和更新内容嵌入后),调用:
func scrollToBottom() {
guard !yourDataSource.isEmpty else { return }
let lastIndex = yourDataSource.count - 1
yourCollectionView.scrollToItem(at: IndexPath(item: lastIndex, section: 0), at: .centeredVertically, animated: true)
}发布于 2019-08-02 10:17:19
重新加载collectionview后,添加以下代码:
let ipath = IndexPath(row: messageList.count - 1, section: 0)
collectionView.scrollToItem(at: ipath, at: .bottom, animated: false)发布于 2019-08-02 12:44:20
您可以将scrollToItem语法放在Vinod的答案中。DispatchQueue.main.async { let ipath = IndexPath(row: messageList.count - 1, section: 0) collectionView.scrollToItem(at: ipath, at: .bottom, animated: false) }
https://stackoverflow.com/questions/57324295
复制相似问题