ios - scrollToRowAtIndexPath 始终从顶部而不是从当前偏移量开始滚动

标签 ios swift uitableviewautomaticdimension

在我的 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/

相关文章:

swift - UITableViewAutomaticDimension-10.0

ios - 隐藏 UITableViewCell 中的 UI 元素并根据调整单元格大小

ios - 生成二进制文件在 iTunes 连接中不可见

ios - 如何将一个 View Controller 方向单独强制/锁定到 landscapeRight?

ios - 如何在 xcode (swift) 中从 Json Schema/Json 生成模型对象?

Swift WKWebView 连续拼写检查

ios - 从服务器下载图像后动态制作表格 View 单元格高度

iphone - 检测 iPhone MapView 上开始的捏合手势

ios - 在 swift 3 中使用自定义 View 选择多个日期范围

ios - 获取错误线程 1 SIGABRT