加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – UITableViewController:使用动态行高度滚动到底部会在

发布时间:2020-12-14 05:31:34 所属栏目:百科 来源:网络整理
导读:我有一个正确配置的表视图,根据Ray Wenderlich的指南 here找到动态行高: 我设置约束以从单元格的顶部到底部具有明确的约束线.我还设置了内容拥抱和内容压缩阻力优先级和估计行高. 这是我用来设置表视图的代码: func configureTableView() { // its called
我有一个正确配置的表视图,根据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)nblanbla"
        ])
    }

    //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()工作正常.然后,在动画到新的最后一行之前,您需要再次使用相同的延迟.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读