Generating UIButton Programmatically

uibuttonWhen you are working on an iOS app, you invariably end up creating buttons on your view controllers. For some of the apps, you know exactly where everything goes and you place everything beforehand in your storyboard file. But if your app is more complex, you may want to create the buttons dynamically. This means is that creating a button might be interactive and can depend on the actions of the user. How do we create buttons programmatically? Once they are created, how do we associate actions with them?  

The function given below will create a button programmatically in the master table view. You can modify it to make it work with any kind of view. I have commented the code to explain what each line does.

- (void) createFloatingView
{
    // Create the rectangle to define the button
    CGRect footerRect = CGRectMake(140, 400, 40, 40);
    
    // Create view to hold the button
    self.floatingView = [[[UIView alloc] initWithFrame:footerRect] autorelease];

    // Set the background color to be transparent (or whatever you want it to be)
    self.floatingView.backgroundColor = [UIColor clearColor];
 
    // Create a button. You can change the type according to your needs.
    UIButton* verifyButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    // Extract the button's frame and change the location of the button
    CGRect buttonFrame = verifyButton.frame;
    buttonFrame.origin.x = 0;
    buttonFrame.origin.y = -10;
    buttonFrame.size.width = 40.0f;
    buttonFrame.size.height = 40.0f;
    verifyButton.frame = buttonFrame;

    // Set various properties of the button
    [verifyButton setTitle:@"Add" forState:UIControlStateNormal];
    [verifyButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [verifyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [verifyButton setBackgroundColor:[UIColor blackColor]];

    // The function to be called when the button is tapped. In this case, "myButtonTapped" will be called
    [verifyButton addTarget:self action:@selector(myButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

    // Add the button to the view created earlier
    [self.floatingView addSubview:verifyButton];

    // Add the view to the master view 
    [self.tableView addSubview:self.floatingView];
    [self.tableView bringSubviewToFront:self.floatingView];
}

————————————————————————————————-

One thought on “Generating UIButton Programmatically

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s