Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}

}
like image 208
Oliver Ferris Avatar asked May 07 '18 13:05

Oliver Ferris


People also ask

How do I scroll to the bottom of the table view?

To scroll to the bottom of the table view items, use ScrollToRow. Three parameters are required for this: NSIndexPath: Specify which row item to scroll to. UITableViewScrollPosition: An enumeration of predefined scroll positions.

Is UITableVIew scrollable?

Smooth Scrolling:- As a result, it affects the smoother scrolling experience. In UITableVIew, Scrolling will be smooth through cell reuse with the help of prepareForReuse() method.


1 Answers

let indexPath = IndexPath(item: noOfRows, section: 0)
yourTableView.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.bottom, animated: true)
like image 161
Abhishek Mitra Avatar answered Oct 27 '22 00:10

Abhishek Mitra