ios - 如何在表格 View 底部添加新行 - 聊天消息

标签 ios swift uitableview

每次用户键入消息并单击“发送”时,我都使用以下代码添加新消息。它很好用。但问题是,新消息被插入到 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/

相关文章:

ios - 没有找到合适的申请记录,无法获取等待上传状态

ios - 如何判断一个 'Any'类型的数组是否为空?

ios - 证书不会显示在build设置中的代码签名身份中

ios - 错误 : 'Transaction' is ambiguous for type lookup in this context

ios - 添加标签栏后搜索栏放在导航下方

ios - 带有 UITextFields 的 UITableView 部分

ios - 我们使用此 Asyncimageview 类从 Web 服务获取图像并显示在 UItableview 中,但无法正常工作?

ios - 当多个警报 View 出现在同一个 View Controller 中时,有没有办法错开?

ios - 如何在 swift 4 中从设备容器中的文档文件夹中打开 pdf 文件

ios - textview 文本到数组中