Oliver Ferris
Oliver Ferris

Reputation: 75

Auto scroll to bottom of UITableView

How is it possible to automatically scroll to the bottom of a UIViewController once the page is opened?

Currently when I open the page its scrolled all way to the top.. But I need it at the bottom as that is where the latest messages are

Heres the swift for the table view:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.dataArr.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "messages") as! UITableViewCell        
    cell.selectionStyle = .none
    let message = cell.viewWithTag(100) as! UILabel
    let name = cell.viewWithTag(101) as! UILabel
    let data = self.dataArr[indexPath.row] as! [String:AnyObject]
    message.text = " " + String(describing: data["message"]!) + " "
    name.text = String(describing: data["name"]!)

    return cell
}


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var mapStr = ""
    let data = self.dataArr[indexPath.row] as! [String:AnyObject]
    let message = String(describing: data["message"]!)
    let array = message.components(separatedBy: "\n") as! [String]
    let arrayLoc = message.components(separatedBy: "Location: ") as! [String]
        if arrayLoc.count > 0 {
            mapStr = arrayLoc[1]
        }
    print(mapStr)
    if mapStr.count > 0 {
        self.open(scheme: mapStr)
    }

}

}

Upvotes: 5

Views: 11937

Answers (2)

Abhishek Mitra
Abhishek Mitra

Reputation: 3395

let indexPath = IndexPath(item: noOfRows, section: 0)
yourTableView.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.bottom, animated: true)

Upvotes: 9

J Rattur
J Rattur

Reputation: 101

This worked for me in Swift 4

I have overidden the viewDidAppear function of my UITableViewController class.

override func viewDidAppear(_ animated: Bool) {
    let scrollPoint = CGPoint(x: 0, y: self.tableView.contentSize.height - self.tableView.frame.size.height)
    self.tableView.setContentOffset(scrollPoint, animated: false)
}

Thanks to this post Scroll all the way down to the bottom of UITableView for the answer, note that question's not quite the same, they scroll down on reloadData rather than the screen appearing.

Upvotes: 5

Related Questions