gpt4 book ai didi

ios - 我在使用协议(protocol)传递数据时做错了什么

转载 作者:行者123 更新时间:2023-11-28 07:45:14 25 4
gpt4 key购买 nike

我正在尝试寻找一种“更简洁优雅”的方式在 UIViewController 之间传递数据。因此,我决定继续使用委托(delegate)和协议(protocol)。但是,我未能收到协议(protocol)提供的数据。我做错了什么?

尝试接收协议(protocol)数据并使用它来填充 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
}

为协议(protocol)创造和设定值(value):

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

最佳答案

在您的 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)
}

一旦新 Controller 被推送到屏幕上,您就可以执行“botaoAdcItem”操作,其余的将获得您预期的结果。

关于ios - 我在使用协议(protocol)传递数据时做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51227932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com