我正在建立一个应用程序,有一个用户提交的文章饲料视图。这个视图有一个具有自定义 UITableViewCell
实现的 UITableView
。在这个单元格中,我有另一个用于显示注释的 UITableView
。大意是这样的:
Feed TableView
PostCell
Comments (TableView)
CommentCell
PostCell
Comments (TableView)
CommentCell
CommentCell
CommentCell
CommentCell
CommentCell
最初的提要会下载3条评论以供预览,但是如果有更多的评论,或者用户添加或删除了一条评论,我想通过添加或删除 CommentCells
到 PostCell
内部的评论表来更新提要表视图内部的 PostCell
。我目前使用以下助手来完成这项工作:
// (PostCell.swift) Handle showing/hiding comments
func animateAddOrDeleteComments(startRow: Int, endRow: Int, operation: CellOperation) {
let table = self.superview?.superview as UITableView
// "table" is outer feed table
// self is the PostCell that is updating it's comments
// self.comments is UITableView for displaying comments inside of the PostCell
table.beginUpdates()
self.comments.beginUpdates()
// This function handles inserting/removing/reloading a range of comments
// so we build out an array of index paths for each row that needs updating
var indexPaths = [NSIndexPath]()
for var index = startRow; index <= endRow; index++ {
indexPaths.append(NSIndexPath(forRow: index, inSection: 0))
}
switch operation {
case .INSERT:
self.comments.insertRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None)
case .DELETE:
self.comments.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None)
case .RELOAD:
self.comments.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None)
}
self.comments.endUpdates()
table.endUpdates()
// trigger a call to updateConstraints so that we can update the height constraint
// of the comments table to fit all of the comments
self.setNeedsUpdateConstraints()
}
override func updateConstraints() {
super.updateConstraints()
self.commentsHeight.constant = self.comments.sizeThatFits(UILayoutFittingCompressedSize).height
}
这样可以很好地完成更新。根据预期,在 PostCell
内部添加或删除评论,更新帖子。我正在饲料表中使用自动调整大小的 PostCells
。PostCell
的注释表展开以显示所有的注释,但是动画有点不稳定,当单元格更新动画时,表格会上下滚动大约12个像素。
调整尺寸时的跳跃有点烦人,但是我的主要问题出现在调整尺寸之后。现在,如果我在 feed 中向下滚动,滚动依然平滑,但是如果我在单元格上方向上滚动,我刚刚在添加注释之后调整了大小,feed 会在到达 feed 顶部之前向后跳动几次。我为 Feed 设置了 iOS8
自动调整单元格,如下所示:
// (FeedController.swift)
// tableView is the feed table containing PostCells
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 560
如果删除 estimatedRowHeight
,那么每当单元格高度发生变化时,表就会滚动到顶部。作为一个新的 iOS 开发者,我现在感觉自己被这个问题困住了,可能需要你提供的任何建议。