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



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

CollectionView的问题-

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

ScrollView的问题-

  • 我担心如果所有页面视图控制器都在内存中,每个视图都在其中,是否会出现内存问题

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

PSS-标签的总数不会超过10个,最少为1个

我用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()
}
}
}

最新更新