ios - Passing data between two ViewControllers (delegate) - Swift -
this question has answer here:
- passing data between view controllers 35 answers
i have 2 viewcontroller's.
firstvc
- havelabel
,button
segue "modal"secondvc
- havepickerview
,button
(back firstvc):@ibaction func bntback(sender: anyobject) { self.dissmissviewcontrolleranimatied(true, completion: nil) }
and created delegate in secondviewcontroller
as:
protocol senddatadelegate { func senddata(text:string) }
next:
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 }
my function of pickerview
, in function use 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 error: "fatal error: unexpectedly found nil while unwrapping 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 } }
help me please problem.
1) need set delegate prepareforsegue:
override func prepareforsegue(segue: uistoryboardsegue, sender: anyobject?) { if let viewcontroller = segue.destinationviewcontroller as? secondvc { viewcontroller.delegate = self } }
update:
2) set delegate
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) )} }
Comments
Post a Comment