首页 > 解决方案 > 带有整页单元格的 UICollectionView VS 带有子视图控制器的 UIScrollView

问题描述

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

CollectionView 的问题 -

ScrollView 的问题 -

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

PSS - 选项卡总数不超过 10,最少为 1

标签: iosswiftuiscrollviewuicollectionview

解决方案


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

推荐阅读