从多个UICollectionVIews内的UICollectionViewCell推送新的UICollectionViewController

时间:2019-01-23 22:02:34

标签: swift uicollectionview uicollectionviewcell uicollectionviewlayout uicollectionviewdelegate

我确实尽力为该问题找到解决方案。我尝试使用委托和协议使用其他解决方案,但我的代码无法正常工作。在抱怨我的问题之前,请支持我,让我们成为一个社区。告诉我您是否不理解我的问题或需要其他信息。我仍然可以更改问题或添加其他信息。我真的需要帮助谢谢社区。

方案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,我真的需要您的帮助。

场景II:

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

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

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

第一个collectionView(在第一个单元格内)具有四个customCells。如果单击这些单元格之一,则希望将新的 UICollectionViewController 推送到 UINavigationController 问题2:如何使用委托和协议来做到这一点?

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

enter image description here

1 个答案:

答案 0 :(得分:1)

我要帮你,你问得很好,所以这里有一个例子。我将不回答问题2和3,因为它与问题1基本相同,但协议有所更改。因此,我将尽力向您解释第一个问题:

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

现在说明:

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

<com.example.ui.common.ProgressButton
        android:id="@+id/progress_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="@{() -> viewModel.onProgressButtonClick()}"
        app:buttonText="@string/test"
        app:buttonBackground="@drawable/selectable_button_blue"
/>

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

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)
    }

}

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

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
        }


    }
}

有一个ButtonsCell协议,顶部单元格可以使该协议更新其他collectionViewCells的内容。每当在buttonCell中按下按钮时,都会调用委托并更新// 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 } } } ,由于var model以及在topCell reloadData()中,该模型也传播到内部单元方法我将innerCells的模型设置为与顶部单元格的模型相同。内部单元格中的cellForItem只是充当观察者,因此每当模型更新时,单元格的UI也应更新。

现在,对于问题2和3,我想如果您看一下示例,它基本上是与委托相同的实现。您只需要对协议功能进行一些更改即可添加所需的功能,还可以在其他位置调用委托,例如在内部collectionView的didSet方法中。

希望这会有所帮助。