简体   繁体   中英

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

}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM