在两个ViewController之间传递数据(代理)-Swift
我有两个 ViewController's.
FirstVC
-我有label
和button
同赛格瑞“模式”SecondVC
-我有PickerView
与button
(回FirstVC):@IBAction func bntback(sender: AnyObject) {
self.dissmissViewControllerAnimatied(true, completion: nil)
}
我创建的委托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
可选
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 的全部内容, 来源链接: utcz.com/qa/411365.html