我正在尝试创建一个 ViewController,它将具有可滑动(类似 android 的选项卡)页面。这些页面本身将在其中具有 ScrollView (垂直)和多个 View ,这些 View 将根据响应类型(每个页面的不同网络调用)动态添加。我不能使用 PageViewController,因为我希望页面只占据屏幕的一半。
CollectionView 的问题 -
- 如果单元格将被重复使用(或从内存中删除),我将如何维护单元格 UI 的状态并存储该数据(对于 View 来说尤其困难,因为每个页面中可能有不同类型的 View )
ScrollView 的问题 -
- 我担心如果所有页面 View Controller 都在内存中并且每个 View 都在内存中,是否会出现内存问题
PS - 每个页面中的数据将是 4-10 个堆栈 View ,每个堆栈 View 包含 2-10 个图像/标签或仅包含一个 Collection View
PSS - 标签总数不会超过 10,最少为 1
最佳答案
我用 collectionView 实现了它,因为它应该更有效地利用资源。但是我们需要缓存 View Controller 的状态。这是例子
假设您有 Controller A
,其中包含带有子 Controller 的单元格的 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()
}
}
}
关于ios - 带有整页单元格的 UICollectionView VS 带有 subview Controller 的 UIScrollView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51532336/