ios - Swift : Programatically Create a UIButton with Some Specific Font And Size -


i want create basic uibutton programmatically. example, in view controller 5 uibuttons created dynamically in same row , layout or properties set color, font, , size.

and need add action method specific button.

if wanted programmatically, might think along following lines:

create buttons in for... loop in viewdidload() (or elsewhere, depending on requirements):

    let buttonwidth : cgfloat = self.view.frame.width / 10     let buttonheight : cgfloat = 50      count in 0..<10 {         let newbutton = uibutton(frame: cgrect(origin: cgpoint(x: cgfloat(count) * buttonwidth, y: 50), size: cgsize(width: buttonwidth, height: buttonheight)))         newbutton.backgroundcolor = uicolor.red         newbutton.settitle("button #\(count)", for: uicontrolstate.normal)         newbutton.settitlecolor(uicolor.white, for: uicontrolstate.normal)         newbutton.addtarget(self, action: #selector(self.buttontapped(sender:)), for: uicontrolevents.touchupinside)         newbutton.titlelabel?.font = uifont(name: "arial", size: 10)         newbutton.tag = count         self.view.addsubview(newbutton)     } 

then can implement selector buttontapped(sender: uibutton) follows, retrieving button's tag can tailor action (via switch statement, example):

func buttontapped(sender: uibutton) -> void {     print("\(sender.tag) tapped!")      // more interesting based on tag here... } 

this allows set lot of button actions without lot of different selectors. hope helps.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -