我正在尝试将此字符串从一个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
}
答案 0 :(得分:2)
您可以使用协议
执行此操作制定协议:
protocol NavTitleProtocol{
func setNavTitle(title: String)
}
使您的CollectionViewController符合协议并覆盖setNavTitle方法:
extension YourCollectionViewController: NavTitleProtocol{
func setNavTitle(title: String) {
self.title = title
}
}
在您的单元格中,拥有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)
}
}
在创建collectionView单元格时将collectionViewController指定为委托:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YourIdentifier", for: indexPath) as! YourCollectionViewCell
cell.delegate = self
}
当您在单元格中执行选择器时,将访问delegate属性,并且将调用您在CollectionViewController中重写的方法。
答案 1 :(得分:1)
首先是这一行
let signUpFlowController1 = SignUpFlowController()
创建一个除了显示的实例之外的新实例,因此您必须使用该委托来捕获所呈现的实例
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
cell.myInstance = self
}
class customCell:UICollectionViewCell {
var myInstance:SignUpFlowController!
@objc func getStartedAction() {
let confirmingTapActionButton1 = "Let's Get Started!"
myInstance.welcomeCellPassedStringForAction1 = confirmingTapActionButton1
}
}