swift – UITableViewController:使用动态行高度滚动到底部会在错误的位置开始动画

我有一个正确配置的表视图,根据Ray Wenderlich的指南 here找到动态行高:

我设置约束以从单元格的顶部到底部具有明确的约束线.我还设置了内容拥抱和内容压缩阻力优先级和估计行高.

这是我用来设置表视图的代码

func configureTableView() {
    // its called on viewDidLoad()
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 100.0
}

override func viewDidLoad() {
    super.viewDidLoad()

    configureTableView()

    for i in 1...20 {
        messages.append([
            "title": "foo \(i)","message": "bla \(i)\nbla\nbla"
        ])
    }

    //this is because the actual row heights are not available until the next layout cycle or something like that
    dispatch_async(dispatch_get_main_queue(),{self.scrollToBottom(false)})
}

func scrollToBottom(animated:Bool) {
    let indexPath = NSIndexPath(forRow: self.messages.count-1,inSection: 0)

    self.tableView.scrollToRowAtIndexPath(indexPath,atScrollPosition: UITableViewScrollPosition.Bottom,animated: animated)
}

这就是我添加新行的方式:

@IBAction func addMore(sender:UIBarButtonItem) {
    let message = [
        "title": "haiooo","message": "silver"]

    messages.append(message)

    let indexPath = NSIndexPath(forRow: messages.count-1,inSection: 0)

    tableView.insertRowsAtIndexPaths([indexPath],withRowAnimation: UITableViewRowAnimation.Bottom)

    scrollToBottom(true)
}

使用认行的设置很好.它按预期将行和滚动添加底部.

但是当我在那之后添加新行时,滚动似乎从最后一个单元格开始.当我添加更多单元格时,偏移量似乎会增加.

这是一个显示它发生的GIF:Imgur

它肯定与滚动动画(不是insertRow动画)有关,因为它在动画关闭时正确滚动.

更改estimatedRowHeight会对滚动偏移产生影响,但我找不到修复它的值.

我也尝试使用dispatch_async延迟滚动,但它没有改变任何东西.

你们有什么想法吗?

哇,这是一个有趣的挑战.感谢您发布测试项目.

因此,似乎在添加新行后,表视图认为滚动到的位置有所不同.在我看来是UIKit中的一个错误.因此,为了解决这个问题,我在应用动画之前添加了一些代码来“重置”表格视图.

这就是我最终得到的结果:

@IBAction func addMore(sender:UIBarButtonItem) {
    let message = [
        "title": "haiooo","message": "silver"]
    messages.append(message)

    tableView.reloadData()

    // To get the animation working as expected,we need to 'reset' the table
    // view's current offset. Otherwise it gets confused when it starts the animation.
    let oldLastCellIndexPath = NSIndexPath(forRow: messages.count-2,inSection: 0)
    self.tableView.scrollToRowAtIndexPath(oldLastCellIndexPath,atScrollPosition: .Bottom,animated: false)

    // Animate on the next pass through the runloop.
    dispatch_async(dispatch_get_main_queue(),{
        self.scrollToBottom(true)
    })
}

我无法使用insertRowsAtIndexPaths(_:withRowAnimation :),但reloadData()工作正常.然后,在动画到新的最后一行之前,您需要再次使用相同的延迟.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...