关于ios:在两个ViewControllers(委托)之间传递数据 – Swift

Passing data between two ViewControllers (delegate) - Swift

本问题已经有最佳答案,请猛点这里访问。

我有两个ViewController's.

  • FirstVC-I具有EDOCX1,2,EDCX1,3,与SeGuE"MODE"

  • SecondVC—我有PickerViewbutton(回到firstvc):

    1
    2
    3
    @IBAction func bntback(sender: AnyObject) {
              self.dissmissViewControllerAnimatied(true, completion: nil)
        }
  • 我在SecondViewController中创建了一个代表:

    1
    2
    3
    protocol SendDataDelegate {
       func sendData(text:String)
    }

    下一步:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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中的职能,在此职能中,我将我的代表用作:

    1
    2
    3
    4
    5
    6
    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:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    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)您需要将委托设置为PrepareForSegue:

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

    更新:

    2)将delegate设置为可选

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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)
            )}
        }