ios - How to pass values out of reusable PickerView.xib in swift -


i created reusable uipickerview:

enter image description here

pickerview.swift:

class pickerview: uiview, uipickerviewdelegate, uipickerviewdatasource {      @iboutlet weak var pickerview: uipickerview!      var labels: [string] = [] {         didset {             self.pickerview.reloadallcomponents()         }     }      required init?(coder adecoder: nscoder) {         super.init(coder: adecoder)         bundle.main.loadnibnamed("pickerview", owner: self, options: nil)         self.addsubview(pickerview)     }      func numberofcomponents(in pickerview: uipickerview) -> int {         return 1     }     func pickerview(_ pickerview: uipickerview, numberofrowsincomponent component: int) -> int {         return labels.count     }     func pickerview(_ pickerview: uipickerview, titleforrow row: int, forcomponent component: int) -> string? {         return labels[row]     }         } 

this code makes can initialize uipickerview setting class of uiview pickerview:

enter image description here

and add data uipickerview, create outlet , add data via outlet. so, viewcontroller.swift file looks this:

viewcontroller.swift:

class viewcontroller: uiviewcontroller {      @iboutlet weak var pickerview: pickerview!      override func viewdidload() {         super.viewdidload()         self.pickerview.labels = ["label1","label2","label3"]     } } 

here's question: how can pass didselectrow value out of picker use in viewcontroller.swift?

create custom protocol

protocol mypickerdelegate: nsobjectprotocol {     func didselectsomething(some: string) } 

create instance inside pickerview.swift like

weak var mydelegate: mypickerdelegate? 

then in viewdidload

self.pickerview.mydelegate = self 

then make uiviewcontroller conform protocol

extension viewcontroller: mypickerdelegate {     func didselectsomething(some: string) {        // self.dostuff()     } } 

then inside pickerview.swift call didselectrow , inside it

self.mydelegate?.didselectsomething(some: "somevalue") 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -