草庐IT

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

coder 2023-09-15 原文

我已经有一个 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!
        }
    
    }
    

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

    有关ios - 另一个 Collection View 中的 Collection View : section header or cell?的更多相关文章

    1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

      总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

    2. ruby - 其他文件中的 Rake 任务 - 2

      我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

    3. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

      作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

    4. ruby-on-rails - Rails 3 中的多个路由文件 - 2

      Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

    5. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

      使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

    6. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

      我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

    7. ruby-on-rails - 渲染另一个 Controller 的 View - 2

      我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

    8. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

      我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

    9. ruby-on-rails - Rails 应用程序中的 Rails : How are you using application_controller. rb 是新手吗? - 2

      刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr

    10. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

      我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

    随机推荐