ios - How to dynamically add an action to a UIButton -
i noticed had lot of functions dynamically add buttons in 1 of view controllers, goes against dry principle.
to fix this, wrote hit-everything configurebutton function:
func configurebutton (button: uibutton, action: string, title: string, pos: [cgfloat]) { button.addtarget(self, action: action, forcontrolevents: uicontrolevents.touchupinside) // ^ throws error // button.addtarget(self, action: "gotoscanner", // forcontrolevents: uicontrolevents.touchupinside) /* configure else */ self.view.addsubview(button) } when had zillion different functions, wrote like
button.addtarget(self, action: "gotoscanner", // <-- note string forcontrolevents: uicontrolevents.touchupinside) in each of them, "gotoscanner" function want called on tap.
i want able dynamically pass action parameter button.addtarget configurebutton:
configurebutton(scanbutton, action: "gotoscanner", title: "scan", pos: [36.0, 300]) i tried passing closure () -> (), didn't work.
how can approach problem?
your method should
func configurebutton (button: uibutton, action: selector, title: string, pos: [cgfloat]) note how uses selector instead of string.
this because swift has no built in implementation of selector, you pass string , string literal type inferred selector (just how entering number literal work both int, float, nsnumber, etc).
Comments
Post a Comment