如何在TableView的底部添加新行-聊天消息 [英] How to add new rows at bottom of tableview - chat messages
问题描述
我使用以下代码在每次用户键入消息并单击发送"时添加新消息.效果很好.但是问题是,新消息将插入到表格视图的顶部.我希望将其插入底部.
I'm using the following code to add new messages every time the user types a message and click 'send'. It works great. But the problem is, new messages are inserted at the top of the table view. I want it to be inserted at the bottom.
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var messagesTable: UITableView!
@IBOutlet var messageTextBox: UITextField!
var messageArray = [String]()
@IBAction func sendMessage(sender: AnyObject) {
messageArray.append(messageTextBox.text!)
messagesTable.reloadData()
messageTextBox.text = ""
}
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messageArray.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//self.messagesTable.contentInset = UIEdgeInsetsMake(messagesTable.frame.height,0,0,0)
let cell = NSBundle.mainBundle().loadNibNamed("AgentMessageText", owner: self, options: nil)?.first as! AgentMessageText
cell.messageText.text = messageArray[indexPath.row]
return cell
}
}
下面的代码将行插入到底部.但是新插入的行在视点下方.那就是我们每次必须滚动才能看到它
The below code insert rows to bottom. But the newly inserted rows are below the view point. That is we have to scroll to see it every time
self.messagesTable.contentInset = UIEdgeInsetsMake(messagesTable.frame.height,0,0,0)
推荐答案
此问题的常见解决方案是翻转表格视图(使单元格停留在底部),然后翻转单元格以使内容正确定位.
A common solution to this problem is to flip the tableview (so cells stick to the bottom) then flip the cells so the content is oriented properly.
示例:
override func viewDidLoad() {
super.viewDidLoad()
//flips the tableview (and all cells) upside down
messagesTableView.transform = CGAffineTransformMakeScale(1, -1)
}
...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
...
//flips the cell to appear oriented correctly
cell.transform = CGAffineTransformMakeScale(1, -1)
对于Swift 4
请注意,对于Swift 4.0,上述转换函数如下所示
Just to be clear, for Swift 4.0 the above transform function is as per below
CGAffineTransform(scaleX: 1, y: -1)
这篇关于如何在TableView的底部添加新行-聊天消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!