selector - Programming a UIButton is not working in Swift 4 Xcode 9 Beta 6, Cannot add target -
in past had no problem creating uibutton programmatically, ever since i've been using xcode 9 , swift 4, cannot find way make error go away.
//adding target uibutton func positionstartbutton(xoffset: float){ startbutton.frame = cgrect(x: int(0 - 40 + xoffset), y: 0, width: 80, height: 80) startbutton.setimage(#imageliteral(resourcename: "logo_final_white_face"), for: .normal) startbutton.addtarget(self, action: "pressbutton:", for: .touchupinside) scrollview.addsubview(startbutton) } //the target function func pressbutton(_ sender: uibutton){ print("\(sender)") }
error message: 'nsinvalidargumentexception', reason: '-[playing.mainmenuviewcontroller pressbutton:]: unrecognized selector sent instance 0x10440a6b0'
two points.
first, since swift 2.2 (bundled xcode 7.3, released more year ago), recommended selector notation #selector(...)
. using notation, may more useful diagnostic messages, using other notation.
(you should not ignore warnings displayed recommended settings.)
seconde, in swift 4, need explicitly annotate methods invoked through selector @objc
. (in limited cases, swift implicitly applies notation, not many.)
so, code shown should be:
//adding target uibutton func positionstartbutton(xoffset: float){ startbutton.frame = cgrect(x: int(0 - 40 + xoffset), y: 0, width: 80, height: 80) startbutton.setimage(#imageliteral(resourcename: "logo_final_white_face"), for: .normal) startbutton.addtarget(self, action: #selector(self.pressbutton(_:)), for: .touchupinside) //<- use `#selector(...)` scrollview.addsubview(startbutton) } //the target function @objc func pressbutton(_ sender: uibutton){ //<- needs `@objc` print("\(sender)") }
this not critical, should better follow simple coding rule of swift -- type names capitalized.
better rename positionstartbutton
, startbutton
, scrollview
, if think may have chance show code publicly.
Comments
Post a Comment