【问题标题】:Push a new UICollectionViewController from a UICollectionViewCell that is inside of multiple UICollectionVIews从多个 UICollectionVIews 内的 UICollectionViewCell 推送新的 UICollectionViewController
【发布时间】:2019-01-23 22:02:34
【问题描述】:

我真的尽我最大的努力来解决这个问题。我尝试了使用委托和协议的不同解决方案,但我的代码不起作用。在抱怨我的问题之前,请支持我,让我们作为一个社区工作。如果您不理解我的问题或需要其他信息,请告诉我。我仍然可以更改问题或添加其他信息。我真的需要帮助。感谢社区。​​p>

情景一一切正常:

我创建了一个 UINavigationController,其中包含一个名为 HomeController 的 UICollectionViewController 作为 rootViewController。 HomeController 包含一个名为 CustomCell 的自定义 UICollectionViewCell。如果我单击 CustomCells 之一,则会执行 HomeController 类的 didSelectItem 方法。此方法将一个新的 UICollectionViewController 推送到 UINavigationController。代码工作正常。这是我的代码的骨架:

class HomeController: UICollectionViewController{

 override func viewDidLoad() {
collectionView?.register(customCell.self, forCellWithReuseIdentifier: "cellId")

 }
 
 // Call methods to render the cell
  override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) 
        return cell
    }
    
 
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: 100)
    }
    

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            let layout = UICollectionViewFlowLayout()
            let controller = UserController(collectionViewLayout: layout)
            navigationController?.pushViewController(controller, animated: true)
        }
    }

}


class customCell: UICollectionViewCell{
.....
}

关于场景 II 和 III,我真的需要你的帮助。

场景二:

我创建了一个 UINavigationController,其中包含一个名为 MainControllerUICollectionViewConrollerMainController 包含四个不同的自定义单元格(CustomCell1、CustomCell2、CustomCell3、CustomCell4)。单元格是水平可滚动的,每个单元格的宽度和高度占据整个 collectionview。

CustomCell1CustomCell2CustomCell3CustomCell4 包含一个 collectionView整个单元格的宽度和高度

class CustomCell1: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout  {

//create a collectionView  
lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = UIColor.white
        cv.dataSource = self
        cv.delegate = self
        return cv
    }()

.....

}

例如:CustomCell1的collectionView包含3个cell。 collectionView 的第一个单元格有两个按钮 Button1Button2。如果我单击 Button2,我希望同一 collectionView 中的 cell2cell3 的内容发生变化。 问题 1:您如何在这种情况下实现这一目标?带有我的构造的代码示例会非常非常有帮助。

如上所述,CustomCell2 还有一个collectionView,它取Cell 的整个宽度和高度。 CustomCell2 的 collectionView 包含三个 CustomCell。第一个和第二个 CustomCell 有一个 collectionView (cell.indexPath == 0 cell.indexPath ==1)。

第一个 collectionView(位于第一个单元格内)有四个 customCells。如果您单击其中一个单元格,我希望将新的 UICollectionViewController 推送到 UINavigationController问题 2:如何使用委托和协议做到这一点?

第二个collectionView(位于第二个单元格内)也有四个customCells。如果您单击其中一个 customCells,则任务不是将新的 UICollectionView 推送到 NavigationController,而是更改 cell3 的内容 问题 3:我该如何实现这一点,有人能给给我一个我提供的骨架的例子?

【问题讨论】:

    标签: swift uicollectionview uicollectionviewcell uicollectionviewlayout uicollectionviewdelegate


    【解决方案1】:

    我会帮助你的,你问得非常好,所以这里有一个例子来说明它是如何完成的。我不会回答问题 2 和 3,因为它与问题 1 基本相同,但协议有一些变化。所以我会尽量解释你的第一个问题:

    让我从您可以下载的完整示例开始:https://github.com/galots/CollectionView

    现在解释一下:

    您有一个 viewController 来创建前几个单元格,这些是您作为第一张图片提供的 4 个自定义单元格。我想这对你来说很清楚:

    class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    
        lazy var collectionView : UICollectionView = {
            let layout = UICollectionViewFlowLayout()
            layout.scrollDirection = .horizontal
            let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
            collectionView.backgroundColor = .white
            collectionView.dataSource = self
            collectionView.delegate = self
            return collectionView
        }()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
    
            self.view.addSubview(collectionView)
            collectionView.anchor(top: self.view.safeAreaLayoutGuide.topAnchor, leading: self.view.leadingAnchor, bottom: self.view.bottomAnchor, trailing: self.view.trailingAnchor)
            collectionView.register(TopCell.self, forCellWithReuseIdentifier: "topCell")
        }
    
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 1
        }
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "topCell", for: indexPath) as! TopCell
            return cell
        }
    
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize(width: self.collectionView.frame.size.width, height: self.collectionView.frame.size.height)
        }
    
    }
    

    现在,在这些单元格中,您还有其他同时显示不同单元格的 collectionView。所以,到目前为止一切顺利。 BaseCell 只是我为避免一直初始化单元格而创建的一个类。

    class BaseCell : UICollectionViewCell {
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupViews()
        }
    
        func setupViews() { }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    
    }
    
    class TopCell: BaseCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, ButtonCellDelegate {
    
        var model = "Text"
    
        lazy var collectionView : UICollectionView = {
            let layout = UICollectionViewFlowLayout()
            let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
            collectionView.backgroundColor = .white
            collectionView.dataSource = self
            collectionView.delegate = self
            return collectionView
        }()
    
        override func setupViews() {
            super.setupViews()
            self.backgroundColor = .green
            self.addSubview(collectionView)
            collectionView.anchor(top: self.topAnchor, leading: self.leadingAnchor, bottom: self.bottomAnchor, trailing: self.trailingAnchor)
            collectionView.register(ButtonsCell.self, forCellWithReuseIdentifier: "buttonsCell")
            collectionView.register(InnerCollectionViewCell.self, forCellWithReuseIdentifier: "cvCell")
        }
    
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 3
        }
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            if indexPath.item == 0 {
                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "buttonsCell", for: indexPath) as! ButtonsCell
                cell.buttonCellDelegate = self
                return cell
            }
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cvCell", for: indexPath) as! InnerCollectionViewCell
            cell.model = self.model
            return cell
        }
    
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize(width: self.frame.width, height: 150)
        }
    
        func didPressButton(sender: String) {
    
            switch sender {
            case "buttonOne":
                self.model = "Text"
                self.collectionView.reloadData()
            case "buttonTwo":
                self.model = "New Text"
                self.collectionView.reloadData()
            default:
                break
            }
    
    
        }
    }
    

    现在,您将在这里完成大部分工作。

    // Protocol for buttons
    
    protocol ButtonCellDelegate : class { func didPressButton (sender: String) }
    
    // Buttons Cell
    
    class ButtonsCell : BaseCell {
    
        weak var buttonCellDelegate : ButtonCellDelegate?
    
        let buttonOne : UIButton = {
            let button = UIButton(frame: .zero)
            button.setTitle("Button 1", for: .normal)
            button.setTitleColor(.black, for: .normal)
            return button
        }()
    
        let buttonTwo : UIButton = {
            let button = UIButton(frame: .zero)
            button.setTitle("Button 2", for: .normal)
            button.setTitleColor(.black, for: .normal)
            return button
        }()
    
        override func setupViews() {
            super.setupViews()
            self.addSubview(buttonOne)
            buttonOne.anchor(top: self.topAnchor, leading: self.leadingAnchor, bottom: self.bottomAnchor, trailing: nil, size: .init(width: self.frame.width / 2, height: 0))
            buttonOne.addTarget(self, action: #selector(buttonOnePressed), for: .touchUpInside)
            self.addSubview(buttonTwo)
            buttonTwo.anchor(top: self.topAnchor, leading: buttonOne.trailingAnchor, bottom: self.bottomAnchor, trailing: self.trailingAnchor)
            buttonTwo.addTarget(self, action: #selector(buttonTwoPressed), for: .touchUpInside)
        }
    
        @objc func buttonTwoPressed (sender: UIButton) {
            self.buttonCellDelegate?.didPressButton(sender: "buttonTwo")
        }
    
        @objc func buttonOnePressed (sender: UIButton) {
            self.buttonCellDelegate?.didPressButton(sender: "buttonOne")
        }
    }
    
    // Mark
    
    class InnerCollectionViewCell : BaseCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
        var model : String? {
            didSet {
                self.collectionView.reloadData()
            }
        }
    
        lazy var collectionView : UICollectionView = {
            let layout = UICollectionViewFlowLayout()
            layout.scrollDirection = .horizontal
            let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
            collectionView.backgroundColor = .red
            collectionView.dataSource = self
            collectionView.delegate = self
            return collectionView
        }()
    
        override func setupViews() {
            super.setupViews()
            self.addSubview(collectionView)
            collectionView.anchor(top: self.topAnchor, leading: self.leadingAnchor, bottom: self.bottomAnchor, trailing: self.trailingAnchor)
            collectionView.register(InnerCollectionViewSubCell.self, forCellWithReuseIdentifier: "innerCell")
        }
    
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return 3
        }
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "innerCell", for: indexPath) as! InnerCollectionViewSubCell
            cell.model = self.model
            return cell
        }
    
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize(width: 100, height: 100)
        }
    
    }
    
    // Mark
    
    class InnerCollectionViewSubCell : BaseCell {
    
        var model : String? {
            didSet { label.text = model }
        }
    
        let label : UILabel = {
            let label = UILabel(frame: .zero)
            label.textColor = .black
            label.textAlignment = .center
            return label
        }()
    
        override func setupViews() {
            super.setupViews()
            self.addSubview(label)
            label.anchor(top: self.topAnchor, leading: self.leadingAnchor, bottom: self.bottomAnchor, trailing: self.trailingAnchor)
        }
    }
    
    // Extensions
    
    extension UIView {
        func anchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, padding: UIEdgeInsets = .zero, size: CGSize = .zero) {
            translatesAutoresizingMaskIntoConstraints = false
            if let top = top { topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true }
            if let leading = leading { leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true }
            if let bottom = bottom { bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom).isActive = true }
            if let trailing = trailing { trailingAnchor.constraint(equalTo: trailing, constant: -padding.right).isActive = true }
            if size.width != 0 { widthAnchor.constraint(equalToConstant: size.width).isActive = true }
            if size.height != 0 { heightAnchor.constraint(equalToConstant: size.height).isActive = true }
        }
    }
    

    ButtonsCell 有一个协议,可以由顶部单元格遵守,以更新其他 collectionViewCells 的内容。每当在 buttonCell 中按下按钮时,将调用委托并更新 var model,由于 reloadData() 和在 topCell cellForItem 方法中我正在设置模型,此模型也会传播到内部单元格innerCells 的模型与顶部单元的模型相同。内部单元格中的didSet 只是充当观察者,因此每当更新模型时,单元格的 UI 也应该更新。

    现在,对于问题 2 和 3,我想如果你看一下这个例子,它基本上是相同的委托实现。您只需对协议函数进行一些更改以添加您需要的功能,您也可以在其他地方调用委托,例如在内部 collectionViews 的 didSelectItem 方法中。

    希望这会有所帮助。

    【讨论】:

    • 谢谢它的工作。如果您有多个集合视图,那么使用委托和协议会非常复杂。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 2018-12-30
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多