swift - 从多个 UICollectionVIews 内部的 UICollectionViewCell 推送一个新的 UICollectionViewController

标签 swift uicollectionview uicollectionviewcell uicollectionviewlayout uicollectionviewdelegate

我真的尽了最大的努力来找到解决这个问题的方法。我尝试了使用委托(delegate)和协议(protocol)的不同解决方案,但我的代码不起作用。在提示我的问题之前,请支持我,让我们像一个社区一样工作。如果您不明白我的问题或需要其他信息,请告诉我。我仍然可以更改问题或添加其他信息。我真的需要帮助。感谢社区。

场景 I 一切正常:

我创建了一个 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)。单元格是水平可滚动的,每个单元格的宽度和高度占据整个 Collection View 。 enter image description here

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 个单元格。 collectionView 的第一个单元格有两个按钮 Button1Button2。如果我单击 Button2,我希望同一 collectionView 中的 cell2cell3 的内容发生变化。 问题 1:在那种情况下,您如何实现这一点?使用我的构造的代码示例将非常非常有帮助。 enter image description here

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

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

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

enter image description here

最佳答案

我会助您一臂之力,您问得真好,下面是一个如何完成的示例。我不会回答问题 2 和 3,因为它与问题 1 基本相同,但协议(protocol)有一些变化。所以我会尽力解释你的第一个问题:

让我从您可以下载的完整示例开始: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)
    }

}

现在,在这些单元格中,您有其他 collectionViews,它们同时显示不同的单元格。所以,到目前为止一切顺利。 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 有一个协议(protocol),顶部单元格可以遵循该协议(protocol)来更新其他 collectionViewCells 的内容。每当在 buttonsCell 中按下按钮时,将调用委托(delegate)并更新 var model,由于 reloadData() 和,此模型也会传播到内部单元格因为在 topCell cellForItem 方法中,我将 innerCells 的模型设置为与顶部单元格的模型相同。内部单元格中的 didSet 只是充当观察者,因此每当模型更新时,单元格的 UI 也应该更新。

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

希望这对您有所帮助。

关于swift - 从多个 UICollectionVIews 内部的 UICollectionViewCell 推送一个新的 UICollectionViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54336365/

相关文章:

ios - 声明方法不可用,因为 swift 5 中的特定 iOS 版本

ios - 从 Alamofire 下载请求访问文件

快速 Split View Controller 默认单元格

uiimage - tvOS调整ImageWhenAncestorFocused裁剪图像 Collection View 单元格

ios - 收藏查看项目大小和数量

ios - 从单元格中获取标签 - swift

swift - 无法解决 swift 4 中的 Null 问题?

ios - UICollectionView moveItemAtIndexPath :toIndexPath: issues moving items not on screen

ios - CollectionViewCells 不会以编程方式出现 - Swift 5

ios - 调用 didHighlightItemAtIndexPath 而不调用 UICollectionView 的 didSelectItemAtIndexPath