在两个ViewControllers(委托)之间传递数据 - Swift

时间:2015-06-26 13:56:47

标签: ios swift modal-dialog segue

我有两个ViewController's.

  1. FirstVC - 我有labelbutton与segue" modal"

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

    @IBAction func bntback(sender: AnyObject) {
              self.dissmissViewControllerAnimatied(true, completion: nil)
        }
    
  3. 我在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
         }
     }
    

    请帮我解决这个问题。

1 个答案:

答案 0 :(得分:7)

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