启动 UITableView 滚动到底部

Rod*_*uiz 6 iphone uitableview ios swift

如何开始UITableView滚动到最后一个单元格?

  • 没有动画
  • 不是在视图出现之后
  • 甚至在表视图被添加为子视图之后

只是有一个平原UITableView(frame: CGRectZero, style: UITableViewStyle.Plain),当出现在屏幕上时,将开始一直滚动到底部。

我试过了:

// 1
reloadData()
scrollToRowAtIndexPath(
    NSIndexPath(forItem: dataArray.count-1, inSection: 0),
    atScrollPosition: .Top, animated: false
)

// 2
reloadData()
var contentOffset = self.contentOffset
contentOffset.y = CGFloat.max
setContentOffset(contentOffset, animated: false)
Run Code Online (Sandbox Code Playgroud)

在 tableView 的init方法上(在我的子类中)

我也尝试过经典的CGAffineTransformMakeScale(1,-1)hack,但这会使我的单元格粘在底部,我希望它们卡在顶部(但滚动到底部)。(只有当我有几个单元格时才相关,当它们没有填满整个UITableView空间时)

编辑:另一个细节,我正在使用动态单元格UITableViewAutomaticDimension

Muh*_*fan 6

这将滚动到底部而不会出现任何故障,但如果您使用 Tableview 滚动到行属性,则会出现故障。

对于Swift 3使用

self.TableView.reloadData() // To populate your tableview first
//Since we have to wait until the table is reload
 DispatchQueue.main.async {
 let bottomOffset = CGPoint(x: 0, y: self.TableView.contentSize.height - self.TableView.frame.size.height)
 self.TableView.setContentOffset(bottomOffset, animated: false)
 }
Run Code Online (Sandbox Code Playgroud)

对于目标 C使用

[YourTableView reloadData]; // To populate your tableview first

[YourTableView setContentOffset:CGPointMake(0, YourTableView.contentSize.height - YourTableView.frame.size.height)];
Run Code Online (Sandbox Code Playgroud)


aat*_*lyk 1

编辑

动画:假

func scrollBottom() {
    let lastIndex = NSIndexPath(forRow: dataArray.count-1, inSection: 0)
    self.tableView.scrollToRowAtIndexPath(lastIndex, atScrollPosition: UITableViewScrollPosition.Bottom, animated: false)
}
Run Code Online (Sandbox Code Playgroud)

测试代码:

import UIKit

class TableViewController: UITableViewController {

var goButton = UIButton()

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self

    goButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
    goButton.backgroundColor = UIColor.blueColor()
    goButton.addTarget(self, action: #selector(TableViewController.scrollBottom), forControlEvents: .TouchUpInside)
    self.view.addSubview(goButton)
}



override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 500
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel?.text = "Hello, World!"

    return cell
}

func scrollBottom() {
    let lastIndex = NSIndexPath(forRow: 499, inSection: 0)
    self.tableView.scrollToRowAtIndexPath(lastIndex, atScrollPosition: UITableViewScrollPosition.Bottom, animated: false)
}

}
Run Code Online (Sandbox Code Playgroud)