我正在 UICollectionViewCell 中显示 UIViewController。每页一个单元格。问题是,当我滑动到下一页时,内存不断增加并且永远不会回来。
这是相关代码。
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let newsVC: NewsTableVC = {
return storyboard?.instantiateViewController(withIdentifier: "NewsListVC")
}() as! NewsTableVC
let cell = pagerCollectionView.dequeueReusableCell(withReuseIdentifier: "PageCollectionViewCell", for: indexPath) as! PageCollectionViewCell
//Wraping ViewController in CollectionView Cell
return wrapAndGetCell(viewColtroller: newsVC, cell: cell)
}
func wrapAndGetCell(viewColtroller: UIViewController, cell: PageCollectionViewCell) -> PageCollectionViewCell{
//setting tag to remove view when it's being reused
viewColtroller.view.tag = PageCollectionViewCell.SUBVIEW_TAG
addChild(viewColtroller)
viewColtroller.view.frame = cell.contentView.bounds
cell.contentView.addSubview(viewColtroller.view)
viewColtroller.didMove(toParent: self)
return cell
}
这是 collectionViewCell 类
class PageCollectionViewCell: UICollectionViewCell {
static let SUBVIEW_TAG: Int = 1000
override func prepareForReuse(){
super.prepareForReuse()
let subViews = self.contentView.subviews
for subView in subViews{
if subView.tag == PageCollectionViewCell.SUBVIEW_TAG{
subView.removeFromSuperview()
print("subView removed")
}
}
}
}
我猜问题是在每个单元格中添加 subview ,但我也在 perpareForReuse()
方法中删除了 subview 。
请帮助我找出问题所在。
最佳答案
问题在于,每次单元格出队时,您都会创建一个新的 NewsTableVC
。您所需要做的只是重用相同的 View Controller ,而不是每次获取单元格时创建一个新的 View Controller 。
创建一个 [NewsTableVC]
类型的数组,然后执行以下操作:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let newsVC = self.newsVCArray[indexPath.item]
let cell = pagerCollectionView.dequeueReusableCell(withReuseIdentifier: "PageCollectionViewCell", for: indexPath) as! PageCollectionViewCell
//Wraping ViewController in CollectionView Cell
return wrapAndGetCell(viewColtroller: newsVC, cell: cell)
}
这应该可以解决您的内存问题,但是创建添加 viewController 的 View 作为 collectionViewCell subview 似乎是一件奇怪的事情。除非您有充分的理由这样做,否则我建议您只使用 PageCollectionViewCell
并完全忘记 NewsTableVC
。
我不知道你想要完成什么,但很难想象以这种方式使用 collectionViewCell 的场景。
关于ios - UIViewController里面CollectionViewCell内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53010838/