无法使用委托协议在标签中设置值

时间:2017-08-24 11:16:58

标签: ios swift protocols

enter image description here我正在创建一个带有委托协议的程序,我们在第二个控制器的文本字段中添加值,然后单击“保存”,并将此值设置为上一个viewController中的标签 所有这些都已完成,但值无法设置为标签 有人可以解释一下在主ViewController中触发messageData()方法的原因是什么?

Administrator
import UIKit

protocol SenderViewControllerDelegate {
    func messageData(data: String)
}

class NewViewController: UIViewController {

    //MARK:- Properties

    @IBOutlet weak var firstTextField: UITextField!


    var delegate: SenderViewControllerDelegate?


    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




    @IBAction func SaveFirstValue(_ sender: Any) {
        if delegate != nil{
            if firstTextField.text != nil{
                let data = firstTextField.text
                delegate?.messageData(data: data!)
                dismiss(animated: true, completion: nil)
            }
        }
        }
    }

4 个答案:

答案 0 :(得分:1)

更改此行

"flavour": [{"row_1_flavour_1_value", "row_1_flavour_2_value"},{"row_2_flavour_1_value", "row_2_flavour_2_value"}],
"taste": [{"row_1_taste_1_value", "row_1_taste_2_value"},{"row_2_taste_1_value", "row__taste_2_value"}]

答案 1 :(得分:0)

你在第ViewController.delegate = self行犯了错误

viewController.delegate = self 

表示小“v” ViewController的对象)

<强>更新:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showSendingVc" {
             let objectOfVC = segue.destination as! NewViewController
            objectOfVC.delegate = self
        }
    }

答案 2 :(得分:0)

   `ViewController.delegate = self` should be `viewController.delegate = self`

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showSendingVc" {
                 let viewController : NewViewController = segue.destination as! NewViewController //destination is type NewViewController not ViewController

               // ViewController.delegate = self //Wrong 
                viewController.delegate = self 
            }
        }

答案 3 :(得分:0)

ViewController类中,在ViewDidLoad方法中设置委托,如下所示:

newViewControllerObj. delegate = self

在不调用viewController类的情况下,委托将不会设置所以你必须在ViewController内调用NewViewController类或其他将首先调用的类:

let ViewControllerObj = ViewController()