Passing data between two ViewControllers (delegate) - Swift
本问题已经有最佳答案,请猛点这里访问。
我有两个
1 2 3 | @IBAction func bntback(sender: AnyObject) { self.dissmissViewControllerAnimatied(true, completion: nil) } |
我在
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 } |
我在
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)将
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) )} } |