一尘不染

在两个ViewController之间传递数据(代理)-Swift

swift

我有两个 ViewController's.

  1. FirstVC-我有labelbutton同赛格瑞“模式”

  2. SecondVC-我有PickerViewbutton(回FirstVC):

    @IBAction func bntback(sender: AnyObject) {
          self.dissmissViewControllerAnimatied(true, completion: nil)
    }
    

我创建的委托SecondViewController为:

protocol SendDataDelegate {
   func sendData(text:String)
}

下一个:

class SecondVC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
      var delegate: SendDataDelegate!
      var firstvc = FirstVC()
      var arr = ["First", "Second", "Third"]
      @IBOutlet var pickview: UIPickerView!
      override func viewDidLoad() {
         super.viewDidLoad()
         pickview.dataSource = self
         pickview.selegate = self
     }

我的函数,PickerView在此函数中,我的委托用作:

func pickerView (pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
  var text = arr[row]
  dispatch_async(dispatch_get_main_quene(), {
  self.delegate.sendData(text)//there is an error: "fatal error: unexpectedly found nil while unwrapping an Optional value"
  )}
}

FirstVC:

class FirstVC: UIViewController, SendDataDelegate {
      var data = SecondVC()
      //....
      override func viewDidLoad() {
         super.viewDidLoad()
         self.data.delegate = self
     }
     func sendData (text:String) {
        mylable.text = text
        //or 
        //var txt = text
       //mylable.text = txt
     }
 }

请帮助我解决这个问题。


阅读 429

收藏
2020-07-07

共1个答案

一尘不染

1)您需要将委托设置为prepareForSegue:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let viewController = segue.destinationViewController as? SecondVC {
        viewController.delegate = self
    }
}

更新:

2)设为delegate可选

class SecondVC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    var delegate: SendDataDelegate?
    ...

    func pickerView (pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        var text = arr[row]
        dispatch_async(dispatch_get_main_quene(), {
            self.delegate?.sendData(text)
        )}
    }
2020-07-07