ios - Make a UIButton programmatically in Swift -
i trying build ui's programmatically. how action working? developing swift.
code in viewdidload:
override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. let myfirstlabel = uilabel() let myfirstbutton = uibutton() myfirstlabel.text = "i made label on screen #toogood4you" myfirstlabel.font = uifont(name: "markerfelt-thin", size: 45) myfirstlabel.textcolor = uicolor.redcolor() myfirstlabel.textalignment = .center myfirstlabel.numberoflines = 5 myfirstlabel.frame = cgrectmake(15, 54, 300, 500) myfirstbutton.settitle("✸", forstate: .normal) myfirstbutton.settitlecolor(uicolor.bluecolor(), forstate: .normal) myfirstbutton.frame = cgrectmake(15, -50, 300, 500) myfirstbutton.addtarget(self, action: "pressed", forcontrolevents: .touchupinside) self.view.addsubview(myfirstlabel) self.view.addsubview(myfirstbutton) } func pressed(sender: uibutton!) { var alertview = uialertview(); alertview.addbuttonwithtitle("ok"); alertview.title = "title"; alertview.message = "message"; alertview.show(); }
you're missing colon @ end of selector name. since pressed takes parameter colon must there. pressed function shouldn't nested inside viewdidload.
override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. let myfirstlabel = uilabel() let myfirstbutton = uibutton() myfirstlabel.text = "i made label on screen #toogood4you" myfirstlabel.font = uifont(name: "markerfelt-thin", size: 45) myfirstlabel.textcolor = uicolor.redcolor() myfirstlabel.textalignment = .center myfirstlabel.numberoflines = 5 myfirstlabel.frame = cgrectmake(15, 54, 300, 500) myfirstbutton.settitle("✸", forstate: .normal) myfirstbutton.settitlecolor(uicolor.bluecolor(), forstate: .normal) myfirstbutton.frame = cgrectmake(15, -50, 300, 500) myfirstbutton.addtarget(self, action: #selector(myclass.pressed(_:)), forcontrolevents: .touchupinside) self.view.addsubview(myfirstlabel) self.view.addsubview(myfirstbutton) } @objc func pressed(sender: uibutton!) { var alertview = uialertview() alertview.addbuttonwithtitle("ok") alertview.title = "title" alertview.message = "message" alertview.show() }
edit: updated reflect best practices in swift 2.2. #selector() should used rather literal string deprecated.
Comments
Post a Comment