Creating a Button using Objective C

By | March 26, 2011

Hi,

Sometimes you may need to create some buttons to the View using Objective C code rather than using Interface Builder. Here is how you can do that easily and efficiently.
//You can create button with type. Here I am creating a Custom Button

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];

//Then what? Give action to be performed on it!

[myButton addTarget:self action:@selector(newAction:)
forControlEvents:UIControlEventTouchUpInside];

//Giving Background, Frame & Title to the button

myButton.frame = CGRectMake(0, 0, 80, 40);
[myButton setBackgroundImage:[UIImage imageNamed:@"buttonImage.png"] forState:UIControlStateNormal];
[myButton setTitle:@"Go Next!" forState:UIControlStateNormal];

//Finally what?? Add it to the View

[self.view addSubview:myButton];

You can create any number of UIButtons like this!
🙂

Leave a Reply

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