Gijo Varghese Gijo Varghese - 1 month ago 14
iOS Question

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)

Answer

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.

Example:

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