每次用户键入消息并单击“发送”时,我都使用以下代码添加新消息。它很好用。但问题是,新消息被插入到 TableView 的顶部。我希望它插在底部。
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
}
}
下面的代码将行插入到底部。但是新插入的行在视点下方。那就是我们每次都必须滚动才能看到它
self.messagesTable.contentInset = UIEdgeInsetsMake(messagesTable.frame.height,0,0,0)
最佳答案
此问题的常见解决方案是翻转 tableview(使单元格粘在底部),然后翻转单元格以使内容正确定向。
例子:
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,上面的转换函数如下所示
CGAffineTransform(scaleX: 1, y: -1)
关于ios - 如何在表格 View 底部添加新行 - 聊天消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40157645/