【发布时间】:2019-07-20 08:36:12
【问题描述】:
我有一个 UITableViewController,其中有要隐藏的单元格。
我目前正在做的是隐藏 heightForRowAt 返回 0 的单元格和 cellForRowAt 返回 isHidden = false 的单元格。但由于我使用的是这个解决方案,我注意到当我在 tableView 中滚动时应用程序变慢了。
// Currently returning a height of 0 for hidden cells
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let post = timeline?.postObjects?[indexPath.row], post.hidden ?? false {
return 0.0
}
return UITableView.automaticDimension
}
// And a cell with cell.isHidden = false (corresponding to identifier "hiddenCell")
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let post = timeline?.postObjects?[indexPath.row] {
if post.hidden ?? false {
return tableView.dequeueReusableCell(withIdentifier: "hiddenCell", for: indexPath)
} else {
return (tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell).with(post: post, timelineController: self, darkMode: isDarkMode())
}
}
}
我在想为什么不对数组应用过滤器以完全删除tableView的隐藏单元格,但我不知道每次过滤它们是否对性能很好......
// Returning only the number of visible cells
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return timeline?.postObjects?.filter{!($0.hidden ?? false)}.count
}
// And creating cells for only visible rows
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let post = timeline?.postObjects?.filter{!($0.hidden ?? false)}[indexPath.row] {
return (tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell).with(post: post, timelineController: self, darkMode: isDarkMode())
}
}
什么是最好的选择?生成单元格时隐藏单元格(第一个)还是将它们排除在列表中(第二个)?
【问题讨论】:
-
尝试这两种方法。测试性能并确定哪个更适合您。
标签: ios swift uitableview