使用协议传递数据时,我在做什么错

时间:2018-07-08 00:25:01

标签: ios swift xcode uitableview

我正在尝试找到一种“简洁优雅”的方法来在UIViewControllers之间传递数据。因此,我决定继续使用代理和协议。但是,我未能收到我的协议提供的数据。我在做什么错了?

尝试接收协议数据并将其用于填充UITableView:

class ViewController: UIViewController, CLLocationManagerDelegate,  UITableViewDataSource, dataReceivedDelegate {

    func dataReceived(nome: String, foto: UIImage, qtd: Int) {
        nomeReceived = nome
        self.qtd = qtd
        self.itensTableView.reloadData()

    }

    @IBOutlet weak var itensTableView: UITableView!
    var arrayNomes = NSMutableArray()
    var nomeReceived = ""
    var qtd:Int = 0
    var objetos = [Objeto]()

    //TableView
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

//        let item = objetos[indexPath.row]
        let cell = itensTableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! tableviewCell
        cell.nameCell.text = nomeReceived //Nil value
//        cell.imageViewCell.image = item.foto //Nil value
        return cell
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return qtd
    }
    override func viewDidAppear(_ animated: Bool) {
        let controller = storyboard?.instantiateViewController(withIdentifier: "addVc") as! adicionarNovoItemVc
        controller.delegate = self
    }

为协议创建并设置值:

import UIKit

protocol dataReceivedDelegate {
    func dataReceived(nome:String,foto:UIImage,qtd:Int)
}

class adicionarNovoItemVc: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {

    @IBOutlet weak var textFieldNome: UITextField!
    let imagePicker = UIImagePickerController()
    @IBOutlet weak var namePreview: UILabel!
    @IBOutlet weak var imagePreview: UIImageView!
    let picker = UIImagePickerController()

    var delegate:dataReceivedDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.textFieldNome.delegate = self
        // Do any additional setup after loading the view.

    }
      @IBAction func botaoAdcItem(_ sender: UIButton) {
        if (self.namePreview!.text != nil) && (self.imagePreview!.image != nil) {

            delegate?.dataReceived(nome: self.namePreview.text!, foto: self.imagePreview.image!, qtd: 1)


            self.navigationController?.popViewController(animated: true)
        }
        else {return}
}

1 个答案:

答案 0 :(得分:0)

在ViewController中,将操作添加到按钮,

func buttonAction(sender: UIButton!) {
    let storyboard = UIStoryboard.init(name: "yourStoryboarName", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "addVc") as! adicionarNovoItemVc
    controller.delegate = self
    self.navigationController?.pushViewController(controller, animated: true)
}

一旦在屏幕上按下了新控制器,您就可以执行“ botaoAdcItem”操作,其余的将获得预期的结果。