【发布时间】:2015-03-15 19:04:02
【问题描述】:
我正在构建一个应用程序,该应用程序具有用户提交的帖子的提要视图。这个视图有一个 UITableView 和一个自定义的 UITableViewCell 实现。在这个单元格内,我有另一个 UITableView 用于显示 cmets。要点是这样的:
Feed TableView
PostCell
Comments (TableView)
CommentCell
PostCell
Comments (TableView)
CommentCell
CommentCell
CommentCell
CommentCell
CommentCell
初始提要将下载 3 个 cmets 以供预览,但如果有更多 cmets,或者如果用户添加或删除评论,我想通过添加或更新提要表视图内部的 PostCell将CommentCells 删除到PostCell 内的cmets 表中。我目前正在使用以下助手来完成此操作:
// (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 中添加或删除了 cmets 来更新帖子。我在 feed 表中使用自动调整大小 PostCells。 PostCell 的 cmets 表展开以显示所有 cmets,但动画有点生涩,在单元格更新动画发生时,表有点上下滚动十几个像素。
调整大小时的跳跃有点烦人,但我的主要问题是在此之后。现在,如果我在提要中向下滚动,滚动会像以前一样平滑,但如果我在添加 cmets 后刚刚调整大小的单元格上方向上滚动,提要会在到达提要顶部之前向后跳几次。我为 Feed 设置了 iOS8 自动调整单元格大小,如下所示:
// (FeedController.swift)
// tableView is the feed table containing PostCells
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 560
如果我删除estimatedRowHeight,表格只会在单元格高度发生变化时滚动到顶部。我现在对此感到很困惑,作为一个新的 iOS 开发人员,可以使用您可能拥有的任何技巧。
【问题讨论】:
标签: ios uitableview swift ios8