自动滚动到UITableView底部

5

如何在UIViewController打开页面后自动滚动到底部?

当前,当我打开页面时它滚动到了顶部.. 但是我需要它在底部,因为那里有最新的消息。

这是表格视图的Swift代码:

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

}

}

4
可能是 如何在表格视图中自动滚动?(Swift) 的重复问题。 - mburesh
我已经查看了这个解决方案,但似乎对我无效 :( 它会抛出错误。 - Oliver Ferris
2个回答

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

如果您希望在视图出现时使表格视图滚动,则将其添加到viewwillappear方法中,但请记住,viewwillappear每次都会调用,其他选项是在viewdidload方法中。 - Vinaykrishnan
@OliverFerris 如果你已经有了数据,那么你可以把这个代码放在 viewDidAppear 中。如果你是在进入相应的 ViewController 后获取数据,那么在获取到所有数据后,你可以把这段代码放在那里。 - Abhishek Mitra
我明白了!但是现在当我尝试传递noOfRows时,我得到了一个未解决的标识符:( - Oliver Ferris
它是 noOfRows - 1。 - Dot Freelancer
@OliverFerris,请将您的tableview数组计数替换为noOfRows。 - Neeraj Joshi

5

这个方法适用于Swift 4。

我重写了UITableViewController类的viewDidAppear函数。

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

感谢这篇文章《将UITableView滚动到底部》的回答,注意该问题与此不完全相同,它们是在调用reloadData时滚动而非显示屏幕。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接