Ios 将值从按钮传递到查看控制器字典
我试图将特定数据从按钮集合视图单元格标题中的按钮传递到视图控制器,并将该值放入数组中。我有一个CollectionViewCell.swift和ViewController.swift,希望从CollectionViewCell.swift传递字符串并将其附加到ViewController.swift中的数组。不确定如何将其传递到ViewController.swift以及如何将该值添加到视图控制器文件的数组中 结构操作对我不起作用。不确定按下按钮时如何将特定于按钮的数据传递给ViewController.swiftIos 将值从按钮传递到查看控制器字典,ios,swift,Ios,Swift,我试图将特定数据从按钮集合视图单元格标题中的按钮传递到视图控制器,并将该值放入数组中。我有一个CollectionViewCell.swift和ViewController.swift,希望从CollectionViewCell.swift传递字符串并将其附加到ViewController.swift中的数组。不确定如何将其传递到ViewController.swift以及如何将该值添加到视图控制器文件的数组中 结构操作对我不起作用。不确定按下按钮时如何将特定于按钮的数据传递给ViewContr
@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
在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
}
}
我是在视图控制器类中还是在类外部添加集合视图?与扩展ViewController行相同?是的,因为ViewController包含集合视图。扩展是在类之外、模块中的任何位置编写的。
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
}
}