ios - 将值从按钮传递到视图控制器字典
问题描述
我正在尝试将特定数据从集合视图单元格(按钮的标题)中的按钮传递到视图控制器并将该值放入数组中。我有一个 CollectionViewCell.swift 和 ViewController.swift 并且想从 CollectionViewCell.swift 传递字符串并将其附加到 ViewController.swift 中的数组中。不知道如何将它传递到 ViewController.swift 以及如何将该值添加到 View Controller 文件中的数组中。
结构操作对我不起作用。不确定按下按钮时如何将特定于按钮的数据传递给 ViewController.swift。
@IBAction func myButton(_ sender: UIButton) {
let name = sender.title(for: .normal) ?? String()
//I Want to send name to view controller and put it into an array in the ViewController.swift
解决方案
protocol collectionViewCellDelegate {
func sendBackTheName(string : String)
}
在 collectionViewCell.swift 中
var delegate : collectionViewCellDelegate?
@IBAction func myButton(_ sender: UIButton) {
let name = sender.title(for: .normal) ?? String()
//I Want to send name to view controller and put it into an array in the ViewController.swift
delegate?.sendBackTheName(string : name)
}
在 viewController.swift 中,添加这一行,
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// do your works
cell.delegate = self
return cell
}
extension ViewController : collectionViewCellDelegate {
func sendBackTheName(string : String) {
array.append(string) // assuming array is declared previously
}
}
推荐阅读
- regex - 如何在 perl 中使用正则表达式模式匹配字符串,如 [aaa-bbb.com]
- html - 如何配置模板使生成的 ts 文件不带双引号
- sql - Dbeaver SQL常用表达式表题
- java - Java LocalDate 如何使用
- ios - 在 XCode 12 中找不到 x86_64 的符号 - 仅限模拟器
- javascript - 在 React 中验证样式化组件的非空字符串
- ios - 如何在 SWIFT UI 主体内运行函数?
- c# - 单例对象中的多个 Elasticsearch 连接在控制器类中获取一个特定的单例弹性搜索
- python-3.x - Python3如何在没有编码的情况下获取原始字节字符串?
- c# - C# Unity2D 是否可以基于字符串调用脚本?