ios - 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
}
解决方案
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.
推荐阅读
- powershell - PowerShell:Invoke-RestMethod - 显示百分比进度
- android - 调用返回类型必须参数化为 Call
或调用改造 API 时调用异常 - c# - C# 使用 `byte[]` 中的 `OpenXml` 打开 excel 文件时出现问题
- php - 数组 - 只保留键“别名”以“a”开头的条目
- azure-aks - Azure Kubernetes 服务节点池如何指定 OS 磁盘类型?
- sql - postgresql sql表中获取列不存在错误
- android - 带有 Jetpack 导航的工具栏中的后退按钮不起作用(对于第一个目的地)
- python-3.x - 如何根据其他列值条件区分第一个值和最后一个值
- python - 熊猫应用功能并更新数据框的副本
- sql - 在单个列中同时显示员工的 UID 和姓名