我有两个ViewController's.
FirstVC
- 我有label
和button
与segue" modal"
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
}
}
请帮我解决这个问题。
答案 0 :(得分:7)
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)
)}
}