2016-06-11 67 views
1

我有一个从实时数据库接收数据的表视图。这些数据是从表格视图底部添加的,所以此表格视图必须向下滚动以显示新数据。在swift中向下滚动tableView?

我发现了一个方法来做到这一点,但我不满意,因为滚动总是从列表的顶部开始。不是很漂亮。

下面是这个方法的代码:

func tableViewScrollToBottom(animated: Bool) { 

    let delay = 0.1 * Double(NSEC_PER_SEC) 
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) 

    dispatch_after(time, dispatch_get_main_queue(), { 

     let numberOfSections = self.clientTable.numberOfSections 
     let numberOfRows = self.clientTable.numberOfRowsInSection(numberOfSections-1) 

     if numberOfRows > 0 { 
      let indexPath = NSIndexPath(forRow: numberOfRows-1, inSection: (numberOfSections-1)) 
      self.clientTable.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Bottom, animated: animated) 
     } 

    }) 
}` 

有以只从原来的位置滚动修改该法的方式进行?

+0

这个问题真的出现在滚动逻辑中吗?或者在你调用这个之前你正在做一个'reloadData'?调用'reloadData'将始终滚动到顶部。如果可以的话,为所添加的行执行'reloadRowsAtIndexPaths'将防止滚动到顶部。 – Rob

+0

确实你是对的我做一个reloadData。我正在尝试reloadRowsAtIndexPaths,但暂时不起作用。 –

+0

其实我注意到,即使我删除reloadData,当我插入一行时,表视图向上滚动。这有什么理由吗? –

回答

2

问题可能是行如何插入表中。例如,如果您添加行使用这样的事情结束后,你会得到一个非常流畅的UI:

@IBAction func didTapAddButton(sender: AnyObject) { 
    let count = objects.count 
    var indexPaths = [NSIndexPath]() 

    // add two rows to my model that `UITableViewDataSource` methods reference; 
    // also build array of new `NSIndexPath` references 

    for row in count ..< count + 2 { 
     objects.append("New row \(row)") 
     indexPaths.append(NSIndexPath(forRow: row, inSection: 0)) 
    } 

    // now insert and scroll 

    tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: .None) 
    tableView.scrollToRowAtIndexPath(indexPaths.last!, atScrollPosition: .Bottom, animated: true) 
} 

注意,我不重装该表,而是叫insertRowsAtIndexPaths。我关闭了动画,因为我知道它们不在屏幕上,然后我将滚动到该行。

enter image description here

+0

我的表中没有和你一样的行为。在滚动底部之前总会有一种滚动顶部 –

+0

@ Bram'in - 也许你可以用更新表格的代码更新你的问题,然后启动滚动。我怀疑前者,而不是后者。我们需要'可重现的例子](http://stackoverflow.com/help/mcve)。 – Rob