gpt4 book ai didi

ios - 另一个 Collection View 中的 Collection View : section header or cell?

转载 作者:可可西里 更新时间:2023-11-01 01:08:32 25 4
gpt4 key购买 nike

我已经有一个 UICollectionView ,它垂直滚动并显示一组具有固定大小的自定义 UICollectionViewCell

现在我被要求在所有其他单元格顶部显示另一个 UICollectionView,它应该 水平滚动 并且其 单元格大小是动态 (我只会在异步网络调用完成后知道大小)。此外,这个内部集合 View 可能并不总是需要显示 (这取决于从网络调用接收到的数据),但如果是,它应该只显示一次(在所有内容之上)。

我的问题是:处理第二个内部集合 View 的最佳方法应该是什么?我应该将它添加到外部 View Controller 作为它的不同类型的单元格,还是作为节标题?
也许另一种布局方法会更好?

编辑: 更多注意事项:

  • 我需要为内部集合 View 设置动画
  • 整个东西应该是垂直可滚动的,这个内部集合 View 不应该粘在屏幕的顶部
  • 最佳答案

    "how the best way to deal with this second and inner collection view should be?"

    "Should I add it to the outer view controller as a different kind of cell of it, or maybe as a section header?"

    "I'd need to animate the inner collection view when I'm going to show it"

    "The whole thing should be vertically scrollable, this inner collection view should not stick to the top of the screen."



    有时退后一步写出您的需求,独立思考每个需求会有所帮助:

    1) CollectionView 的第一个单元格应该水平滚动。

    2)第一个单元格应该垂直滚动超过屏幕。

    CollectionView 的第一个单元格需要包含一个 CollectionView 本身。

    3a) CollectionView 的其他单元格是静态大小。

    3b) CollectionViews 的第一个单元格是动态大小的。

    需要两个单元类,或者一个具有动态约束和 subview 的单元类。

    4) CollectionView 的第一个单元格应该是动画的。

    第一个单元格的 CollectionView 需要是其动态单元格的委托(delegate)。 (动画发生在 cellForItemAt indexPath 中)

    请记住, UICollectionView 是独立的 View 。 UICollectionViewController 本质上是包含 UIViewControllerUICollectionViewDelegateUICollectionViewDataSourceUICollectionView 。就像任何 UIView 一样,您可以将 UICollectionView 子类化并将其添加到另一个 View 的 subview 中,例如 UICollectionViewCell 。通过这种方式,您可以将集合 View 添加到单元格并将单元格添加到该嵌套集合 View 。您还可以允许嵌套集合 View 处理来自 UICollectionViewDelegateUICollectionViewDataSource 的所有委托(delegate)方法,从而使其模块化和可重用。您可以在 UICollectionView 方法中传递要显示在嵌套 convenience init 的每个单元格中的数据,并允许该类处理动画和设置。这是迄今为止最好的方法,不仅是为了重用,也是为了性能,尤其是当您以编程方式创建 View 时。

    在下面的示例中,我有一个名为 ViewController 的 UICollectionViewController,它将成为所有其他 View 的 View Controller 。

    我也有两个 CollectionViews, ParentCollectionViewHorizontalCollectionView 。 ParentCollectionView 是 UICollectionView 的一个空实现。我可以使用 collectionViewUICollectionViewController 但因为我希望它完全模块化,所以我稍后会将我的 ParentCollectionView 分配给 ViewController 的 collectionView。 ParentCollectionView 将处理 View 中的所有单元格静态单元格,包括包含我们的 Horizo​​ntalCollectionView 的单元格。 Horizo​​ntalCollectionView 将是所有“单元格对象”(您的数据模型)在其便利初始化程序中传递给它的委托(delegate)和数据源。也就是说 Horizo​​ntalCollectionView 将管理它自己的单元格,这样我们的 UICollectionViewController 就不会变胖。

    除了两个 CollectionViews 和一个 UICollectionViewController 之外,我还有两个 UICollectionViewCell 类,一个是静态大小,另一个是动态(随机生成的 CGSize)。为了便于使用,我还有一个将类名作为标识符返回的扩展,我不喜欢将硬编码字符串用于可重用的单元格。这些单元格类别并不是完全不同,可以使用相同的单元格并在 sizeForItemAt indexPathcellForItemAt indexPath 中更改单元格大小,但为了演示起见,我将说它们是完全不同的单元格,需要完全不同的数据模型。

    现在,我们不希望 ParentCollectionView 中的第一个单元出列,这是因为该单元将从内存中删除并扔回队列以供重用,我们当然不希望我们的 Horizo​​ntalCollectionView 随机弹出。为了避免这种情况,我们需要同时注册我们的 StaticCollectionViewCell 和一个只使用一次的通用单元格,因为我添加了一个扩展,该扩展为我提供了单元格的类名,我将使用 UICollectionViewCell 作为标识符。

    我相信你在弄清楚其余部分不会有太多麻烦,这是我的完整实现:

    ViewController.swift
    import UIKit

    class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    // Programmically add our empty / custom ParentCollectionView
    let parentCollectionView: ParentCollectionView = {
    let layout = UICollectionViewFlowLayout()
    let cv = ParentCollectionView(frame: .zero, collectionViewLayout: layout)
    cv.translatesAutoresizingMaskIntoConstraints = false
    return cv
    }()


    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    setup()

    }

    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }

    func setup() {
    // Assign this viewcontroller's collection view to our own custom one.
    self.collectionView = parentCollectionView

    // Set delegate and register Static and empty cells for later use.
    parentCollectionView.delegate = self
    parentCollectionView.register(StaticCollectionViewCell.self, forCellWithReuseIdentifier: StaticCollectionViewCell.identifier)
    parentCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: UICollectionViewCell.identifier)

    // Add simple Contraints
    let guide = self.view.safeAreaLayoutGuide

    parentCollectionView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
    parentCollectionView.leftAnchor.constraint(equalTo: guide.leftAnchor).isActive = true
    parentCollectionView.rightAnchor.constraint(equalTo: guide.rightAnchor).isActive = true
    parentCollectionView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
    }

    // MARK: - CollectionView

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // Erroneous Data from your network call, data should be a class property.
    let data = Array.init(repeating: "0", count: 12)

    // Skip if we dont have any data to show for the first row.
    if (indexPath.row == 0 && data.count > 0) {

    // Create a new empty cell for reuse, this cell will only be used for the frist cell.
    let cell = parentCollectionView.dequeueReusableCell(withReuseIdentifier: UICollectionViewCell.identifier, for: IndexPath(row: 0, section: 0))

    // Programmically Create a Horizontal Collection View add to the Cell
    let horizontalView:HorizontalCollectionView = {
    // Only Flow Layout has scroll direction
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    // Init with Data.
    let hr = HorizontalCollectionView(frame: cell.frame, collectionViewLayout: layout, data: data)
    return hr
    }()
    // Adjust cell's frame and add it as a subview.
    cell.addSubview(horizontalView)
    return cell
    }

    // In all other cases, just create a regular cell.
    let cell = parentCollectionView.dequeueReusableCell(withReuseIdentifier: StaticCollectionViewCell.identifier, for: indexPath)
    // Update Cell.

    return cell
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // 30 sounds like enough.
    return 30
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    //If you need your first row to be bigger return a larger size.
    if (indexPath.row == 0) {
    return StaticCollectionViewCell.size()
    }


    return StaticCollectionViewCell.size()
    }

    }

    ParentCollectionView.swift
    import UIKit

    class ParentCollectionView: UICollectionView {

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
    super.init(frame: frame, collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
    }
    }

    Horizo​​ntalCollectionView.swift
    import Foundation
    import UIKit

    class HorizontalCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    // Your Data Model Objects
    var data:[Any]?

    // Required
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
    super.init(frame: frame, collectionViewLayout: layout)
    }

    convenience init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout, data:[Any]) {
    self.init(frame: frame, collectionViewLayout: layout)

    // Set These
    self.delegate = self
    self.dataSource = self
    self.data = data
    // Setup Subviews.
    setup()
    }

    required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // return zero if we have no data to show.
    guard let count = self.data?.count else {
    return 0
    }
    return count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = self.dequeueReusableCell(withReuseIdentifier: DynamicCollectionViewCell.identifier, for: indexPath)
    // Do Some fancy Animation when scrolling.
    let endingFrame = cell.frame
    let transitionalTranslation = self.panGestureRecognizer.translation(in: self.superview)
    if (transitionalTranslation.x > 0) {
    cell.frame = CGRect(x: endingFrame.origin.x - 200, y: endingFrame.origin.y - 100, width: 0, height: 0)
    } else {
    cell.frame = CGRect(x: endingFrame.origin.x + 200, y: endingFrame.origin.y - 100, width: 0, height: 0)
    }

    UIView.animate(withDuration: 1.2) {
    cell.frame = endingFrame
    }

    return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // See DynamicCollectionViewCell size method, generate a random size.
    return DynamicCollectionViewCell.size()
    }

    func setup(){
    self.backgroundColor = UIColor.white
    self.register(DynamicCollectionViewCell.self, forCellWithReuseIdentifier: DynamicCollectionViewCell.identifier)
    // Must call reload, Data is not loaded unless explicitly told to.
    // Must run on Main thread this class is still initalizing.
    DispatchQueue.main.async {
    self.reloadData()
    }
    }

    }

    DynamicCollectionViewCell.swift
    import Foundation
    import UIKit

    class DynamicCollectionViewCell: UICollectionViewCell {

    /// Get the Size of the Cell
    /// Will generate a random width element no less than 100 and no greater than 350
    /// - Returns: CGFloat
    class func size() -> CGSize {
    let width = 100 + Double(arc4random_uniform(250))
    return CGSize(width: width, height: 100.0)
    }

    override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
    }

    required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
    }

    func setup() {
    self.backgroundColor = UIColor.green
    }
    }

    StaticCollectionViewCell.swift
    import Foundation
    import UIKit

    class StaticCollectionViewCell: UICollectionViewCell {

    /// Get the Size of the Cell
    /// - Returns: CGFloat
    class func size() -> CGSize {
    return CGSize(width: UIScreen.main.bounds.width, height: 150.0)
    }

    override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
    }

    required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
    }

    func setup() {
    self.backgroundColor = UIColor.red
    }


    }

    CollectionViewCellExtentions.swift
    import UIKit

    extension UICollectionViewCell {

    /// Get the string identifier for this class.
    ///
    /// - Returns: String
    class var identifier: String {
    return NSStringFromClass(self).components(separatedBy: ".").last!
    }

    }

    Nested Collection Views

    关于ios - 另一个 Collection View 中的 Collection View : section header or cell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51906411/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com