从按钮将值传递给视图控制器字典

问题描述 投票:-3回答:1

我试图从一个按钮传递特定数据的集合视图细胞(按钮的标题)到视图控制器并把该值在阵列中。我有一个CollectionViewCell.swift和ViewController.swift和想从CollectionViewCell.swift传递字符串并将其追加到在ViewController.swift阵列。不知道如何将它传递到ViewController.swift以及如何将该值添加到一个数组到视图控制器文件。

结构操作并没有为我工作。不知道怎么按下按钮时,特定的数据传递到按钮的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

ios swift
1个回答
1
投票
protocol collectionViewCellDelegate {
    func sendBackTheName(string : String)
}

在uicollectionViewCell.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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.