首页 > 解决方案 > Swift 4:将 UICollectionViewCell 中的字符串传递给 UICollectionViewController

问题描述

我正在尝试将此字符串从一个 UICollectionViewCell 传递给 UICollectionViewController。我想要“让我们开始吧!” 继续我的导航标题...下面是我的代码,我不知道为什么字符串没有通过。

// UICOLLECTIONVIEWCELL --> This is the first UICollectionViewCell
    @objc func getStartedAction() {
        let confirmingTapActionButton1 = "Let's Get Started!"
        let signUpFlowController1 = SignUpFlowController()
        signUpFlowController1.welcomeCellPassedStringForAction1 = confirmingTapActionButton1
    }


// UICollectionViewController --> This is the second UICollectionViewController
    class SignUpFlowController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

        var welcomeCellPassedStringForAction1: String? = nil

        override func viewDidLoad() {
            super.viewDidLoad()
            collectionView?.backgroundColor = .white

            // NAV BAR STUFF BELOW
            self.title = welcomeCellPassedStringForAction1

        }

标签: iosswiftuicollectionviewcell

解决方案


You can do this using a protocol

Make a protocol:

protocol NavTitleProtocol{
func setNavTitle(title: String)
}

Conform your CollectionViewController to the protocol and override the setNavTitle method:

extension YourCollectionViewController: NavTitleProtocol{
func setNavTitle(title: String) {
    self.title = title
}
} 

In your cell, have a delegate property of type NavTitleProtocol:

class YourCollectionViewCell: UICollectionViewCell{
var delegate: NavTitleProtocol?

@objc func getStartedAction() {
    let confirmingTapActionButton1 = "Let's Get Started!"
//   let signUpFlowController1 = SignUpFlowController()
//        signUpFlowController1.welcomeCellPassedStringForAction1 = confirmingTapActionButton1
    delegate?.setNavTitle(title: confirmingTapActionButton1)
}
}

Assign your collectionViewController as the delegate when you create the collectionView cell:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourIdentifier", for: indexPath) as! YourCollectionViewCell
    cell.delegate = self
}

When you perform the selector in your cell, the delegate property will be accessed and the method that you have overriden in your CollectionViewController will be called.


推荐阅读