我有两个 ViewController's.
ViewController's.
FirstVC-我有label和button同赛格瑞“模式”
FirstVC
label
button
SecondVC-我有PickerView与button(回FirstVC):
SecondVC
PickerView
@IBAction func bntback(sender: AnyObject) { self.dissmissViewControllerAnimatied(true, completion: nil) }
我创建的委托SecondViewController为:
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)您需要将委托设置为prepareForSegue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let viewController = segue.destinationViewController as? SecondVC { viewController.delegate = self } }
更新:
2)设为delegate可选
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) )} }