首页 > 解决方案 > 将值从按钮传递到视图控制器字典

问题描述

我正在尝试将特定数据从集合视图单元格(按钮的标题)中的按钮传递到视图控制器并将该值放入数组中。我有一个 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

标签: iosswift

解决方案


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
    }
}

推荐阅读