我有一个 ViewController,它有一个 Collection View 。在每个 Collection View 单元格中,它们都是一个 TableView 。由于该 tableView,我正面临性能问题。当调用 cellforItemAtIndexPath 时,我尝试为每个 CollectionViewCell 重新加载数据。因此,我的 CPU 使用率上升了 90%。我的 ViewController 看起来像这样
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCustomCollectionViewCell", forIndexPath: indexPath) as! MyCustomCollectionViewCell
// This line is causing performance issue
cell.tableView.reloadData()
return cell
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(40, 40)
}
MyCustomCollectionViewCell 看起来像这样
class ChannelCollectionViewCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
@IBOutlet weak var tableView: UITableView!
var delegate: ChannelCollectionViewCellDelegate?
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 10
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 120
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCustomTableViewCell", forIndexPath:
indexPath) as! MyCustomTableViewCell
cell.title = "Testt Title"
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 50
}
}
能否将 cell.tableView.reloadData() 移动到更好的位置,以免导致性能问题
最佳答案
我不这么认为,因为 UITableView
像 UICollectoinView
一样用数据源填充自己,当你出列另一个 UICollectoinViewCell
时你必须调用reloadData()
(因为这个单元格之前可能已经初始化过,你必须重新填充它)。
您可以做的是停止出队(风险自负)。出列是一种内存优化技术,如果您在 collectionView 中只有 10 个单元格,您“可以”直接初始化一个 UICollectionViewCell
并显示它。但是 collectionView 仍然会调用 cellForRowAtIndexPath
所以你必须为每个 indexPaths 缓存所有单元格,如果你已经初始化了单元格,返回它。但是这种技术会占用大量内存,因此您可能会收到大量内存警告。
我猜你正在实现类似 Trello 之类的东西(因为 collectionView 中的 tableView 包含大约 120 行对我来说听起来不合逻辑:/)。如果是这种情况,我建议将您的架构更改为 UIPageViewController
+ UITableViewContoller
。
关于ios - CollectionViewcell 中 tableView 的性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37921750/