ios - Passing data between two ViewControllers (delegate) - Swift -


this question has answer here:

i have 2 viewcontroller's.

  1. firstvc - have label , button segue "modal"

  2. secondvc - have pickerview , 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

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -