我设置约束以从单元格的顶部到底部具有明确的约束线.我还设置了内容拥抱和内容压缩阻力优先级和估计行高.
这是我用来设置表视图的代码:
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) }
但是当我在那之后添加新行时,滚动似乎从最后一个单元格开始.当我添加更多单元格时,偏移量似乎会增加.
它肯定与滚动动画(不是insertRow动画)有关,因为它在动画关闭时正确滚动.
更改estimatedRowHeight会对滚动偏移产生影响,但我找不到修复它的值.
我也尝试使用dispatch_async延迟滚动,但它没有改变任何东西.
你们有什么想法吗?