我有两个 ViewController.
FirstVC
- 我有 label
和 button
与 segue "modal"
FirstVC
- I have label
and button
with segue "modal"
SecondVC
- 我有 PickerView
和 button
(返回 FirstVC):
SecondVC
- I have PickerView
and button
(back to FirstVC):
@IBAction func bntback(sender: AnyObject) {
self.dissmissViewControllerAnimatied(true, completion: nil)
}
我在 SecondViewController
中创建了委托:
And I created delegate in SecondViewController
as:
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
函数,在这个函数中我使用我的委托作为:
My function of PickerView
and in this function I use my delegate as:
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"
)}
}
第一VC:
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) 你需要将delegate设置成prepareForSegue:
1) You need to set delegate into prepareForSegue:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let viewController = segue.destinationViewController as? SecondVC {
viewController.delegate = self
}
}
更新:
2) 将 delegate
设置为可选
2) Set delegate
as Optional
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)
)}
}
这篇关于在两个 ViewController(委托)之间传递数据 - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!