So here I am sharing my learning to create UIButton at runtime and adding it to view.
In following, I am creating UIButton named customButton, setting its location and size on screen and then image for normal and highlighted state.
UIButton* customButton = [UIButton buttonWithType:UIButtonTypeCustom]; [customButton setFrame:CGRectMake(10,10, 100, 100)]; [customButton setImage:[UIImage imageNamed:@"blue-ind.png"] forState:UIControlStateNormal]; [customButton setImage:[UIImage imageNamed:@"red-ind.png"] forState:UIControlStateHighlighted];Then I am specify what function needed to be called when button get pressed using addTarget method of UIButton.
[customButton addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];Finally adding button to view.
[self.view addSubview:customButton];Now when above button is clicked, btnClicked method will be get called. I have used following declaration and definition for btnClicked method.
-(void) btnClicked ;
-(void) btnClicked {
NSLog(@"Custom button clicked");
}
Here is output of above code.






