how to add UIButton programatically

We all know that we can create any UI control from stroryboard or xib file, by drag and drop in storyboard, but there is certain limitations in it, so lets have a look on adding uicontrol programatically .

here is the code for adding uibutton programatically .

UIButton *Button = [[UIButton alloc] initWithFrame:CGRectMake(0,0,100,100)];/ button created button setBackgroundImage :[UIImage imageNamed:@”image.jpg”]];
[self.view addSubview:button] // adding button as subview to your main view.
button.hidden =  NO;

// thats it now button has been created , lets play some other thing with this button

[button setTitle:@”myButton”];

if you don’t want background image and title, instead of that you like displaying graphical title with nice artwork. Simple create your artwork image and you can set that image to uibutton

[button setImage :[UIImage imageNamed:@”artwork.png”] forControlState:UIControlStateNormal];

if you want to change image while click on that button,  you can add highlighted  artwork image and add it like below

[button setImage :[UIImage imageNamed:@”artwork.png”] forControlState:UIControlStateHighLighted];

NOTE: dont forget adding those images in your xcode project (simply drag your image and drop it in your project resources)

next thing we need to add action for button click

[button addTarget:self selector:@selector(buttonEvent) forEventState:UIControlTouchUpInside]

and if you want to change button position to somewhere
button.frame = CGRectMake(0,240,100,100);




Leave a Reply

Your email address will not be published. Required fields are marked *