在我的 UITableView
中,我使用一种方法滚动到最后一个单元格:
WLNetworkClient.sharedClient().createCommentWIthText(commentTextView.text, forItem: item) { error in
defer {
UIAlertController.showAlertFromError(error)
}
if error == nil {
self.fetchedResultsController.fetchRequest.fetchLimit += 1
try! self.fetchedResultsController.performFetch()
self.tableView.reloadData()
self.scrollTableViewToBottom()
}
}
private func scrollTableViewToBottom() {
tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: fetchedResultsController.fetchedObjects!.count - 1, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: true)
}
但这并没有像预期的那样工作,因为即使我在第二个单元格上,表格总是从顶部滚动到最后。如何解决这个问题?
最佳答案
dosdos 答案在 Swift 2 中对我有用 添加小更新
声明ivar
var heightAtIndexPath = NSMutableDictionary()
在函数 viewDidLoad() 中
func viewDidLoad() {
.... your code
self.tableView.rowHeight = UITableViewAutomaticDimension
}
然后添加以下2个方法:
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let height = self.heightAtIndexPath.objectForKey(indexPath)
if ((height) != nil) {
return CGFloat(height!.floatValue)
} else {
return UITableViewAutomaticDimension
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
let height = cell.frame.size.height
self.heightAtIndexPath.setObject(height, forKey: indexPath)
}
SWIFT 3:
var heightAtIndexPath = NSMutableDictionary()
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
let height = self.heightAtIndexPath.object(forKey: indexPath)
if ((height) != nil) {
return CGFloat(height as! CGFloat)
} else {
return UITableViewAutomaticDimension
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let height = cell.frame.size.height
self.heightAtIndexPath.setObject(height, forKey: indexPath as NSCopying)
}
关于ios - scrollToRowAtIndexPath 始终从顶部而不是从当前偏移量开始滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32476407/