带有完整页面单元格的UICollectionView VS带有子视图控制器的UIScrollView

Aka*_*pat 10 uiscrollview ios uicollectionview swift

我正在尝试创建一个可以刷卡(类似于android的标签页)的ViewController.这些页面本身将包含滚动视图(垂直)和多个视图,这些视图将根据响应类型(每个页面的不同网络调用)动态添加.我不能使用PageViewController,因为我希望页面只占用屏幕的一半.

CollectionView的问题 -

  • 如果单元格将被重用(或从内存中删除),我将如何维护单元格UI的状态并存储该数据(对于视图来说尤其困难,因为每个页面可能具有不同类型的视图)

ScrollView的问题 -

  • 我担心如果所有页面视图控制器都在内存中,并且每个视图都存在内存问题

PS - 每页中的数据将是4-10个堆栈视图,每个堆栈视图包含2-10个图像/标签或仅一个集合视图

PSS - 标签总数不超过10,最小值为1

Mik*_*slo 4

我用collectionView实现了它,因为它应该更有效地利用资源。但是我们需要缓存视图控制器的状态。这是例子

假设您有一个控制器A,其中包含带有子控制器的单元格的collectionView。然后在行的单元格中

....
var childrenVC: [Int: UIViewController] = [:]
....
// cell for row
let cell: ChildControllerCell = collectionView.dequeueReusableCell(for: indexPath)
if let childController = childrenVC[indexPath.row] {
   cell.contentView.addSubview(childController.view)
   childController.view.frame = cell.contentView.frame
} else {
   let childViewController = ChildViewController()
   addChildViewController(childViewController)
   childViewController.didMove(toParentViewController: self)
   cell.contentView.addSubview(childController.view)
   childController.view.frame = cell.contentView.frame
   childrenVC[indexPath.row] = childViewController
   cell.childVC = childViewController
}
return cell
....
class ChildControllerCell: UICollectionViewCell {
     var childVC: UIViewController?
     override func prepareForReuse() {
        super.prepareForReuse()
        if !contentView.subviews.isEmpty {
            childVC?.willMove(toParentViewController: nil)
            childVC?.view.removeFromSuperview()
            childVC?.removeFromParentViewController()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)