How do I create a basic UIButton programmatically?

| | August 8, 2015

How can I create a basic UIButton programmatically? For example in my view controller, when executing the viewDidLoad method, three UIButtons will be created dynamically and its layout or properties are set.

26 Responses to “How do I create a basic UIButton programmatically?”

  1. There are plenty of good answers here. This page has a video screen cast of how to add a UIButton and hook up the action with it in Swift.

  2. **

    UIButton *buttonName = [UIButton
    buttonWithType:UIButtonTypeRoundedRect]; [buttonName addTarget:self
    action:@selector(aMethod:)forControlEvents:UIControlEventTouchDown];
    [buttonName setTitle:@”Show View” forState:UIControlStateNormal];
    buttonName.frame = CGRectMake(80.0, 210.0, 160.0, 40.0); [view
    addSubview:buttonName];

    **

  3. Objective-C

    UIButton *but= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [but addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
     [but setFrame:CGRectMake(52, 252, 215, 40)];
    [but setTitle:@"Login" forState:UIControlStateNormal];
    [but setExclusiveTouch:YES];
    
     // if you like to add backgroundImage else no need
       [but setbackgroundImage:[UIImage imageNamed:@"XXX.png"] forState:UIControlStateNormal];
    
    [self.view addSubview:but];
    
    -(void) buttonClicked:(UIButton*)sender
     {
    NSLog(@"you clicked on button %@", sender.tag);
     }
    

    Swift

        let myButton = UIButton()
        myButton.setTitle("Hai Touch Me", forState: .Normal)
        myButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
        myButton.frame = CGRectMake(15, 50, 300, 500)
        myButton.addTarget(self, action: "pressedAction:", forControlEvents: .TouchUpInside)
        self.view.addSubview( myButton)
    
    
    func pressedAction(sender: UIButton!) {
       // do your stuff here 
      NSLog("you clicked on button %@", sender.tag)
    }
    
  4. try this:

    first write this in your .h file of viewcontroller

    UIButton *btn;
    

    Now write this in your .m file of viewcontrollers viewDidLoad.

    btn=[[UIButton alloc]initWithFrame:CGRectMake(50, 20, 30, 30)];
    [btn setBackgroundColor:[UIColor orangeColor]];
    [btn setTitle: @"My Button" forState:UIControlStateNormal];
    [btn setTitleColor: [UIColor blueVolor] forState:UIControlStateNormal];
    [btn.layer setBorderWidth:1.0f];
    [btn.layer setBorderColor:[UIColor BlueVolor].CGColor];
    //adding action programatically
    [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    

    write this outside viewDidLoad method in .m file of your view controller

    - (IBAction)btnClicked:(id)sender
    {
      //Write a code you want to execute on buttons click event
    }
    
  5. -(void)addStuffToView
    {
        UIButton *aButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 20, 20)]; //(x, y, width, height of button on screen
        [aButton setTitle:@"Button" forState:UIControlStateNormal];//puts the text on the button
        aButton.titleLabel.font = somefont;//sets the font if one is already stated
        aButton.titleLabel.font = [UIFont fontWithName:@"Arial-MT" size:12];//sets the font type and size
        [aButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];//see back method below
        [aButton setBackgroundImage:[UIImage imageNamed:@"someImage.png"] forState:UIControlStateNormal];//sets the image of the button
        [self.view addSubview:back];
    }
    
    -(void)back
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle.....]
    }
    
    -(void)viewDidLoad
    {
        [super viewDidLoad];
        [self addStuffToView];//adds all items built in this method to the view
    }
    
  6. This is the way i have created the UIButton programmatically

        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];        
        [button addTarget:self action:@selector(aMethod:)
         forControlEvents:UIControlEventTouchUpInside];        
        [button setTitle:@"Show View" forState:UIControlStateNormal];        
        button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    
        [view addSubview:button];
    
  7. Here’s one:

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self 
               action:@selector(aMethod:)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Show View" forState:UIControlStateNormal];
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    [view addSubview:button];
    
  8. Adam Libonatti-Roche on November 30, -0001 @ 12:00 AM

    You can just put the creator instance within a loop and dynamically add names from an array if you so wish.

  9. UIButton * tmpBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [tmpBtn addTarget:self action:@selector(clearCart:) forControlEvents:UIControlEventTouchUpInside];
    tmpBtn.tag = k;
    tmpBtn.frame = CGRectMake(45, 0, 15, 15);
    [tmpBtn setBackgroundImage:[UIImage imageNamed:@"CloseButton.png"] forState:UIControlStateNormal];
    [self.view addSubview:tmpBtn];
    
  10. You can create button by this code.

     UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
     [btn addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchDragInside];
     [btn setTitle:@"click button" forState:UIControlStateNormal];
      btn.frame = CGRectMake(50, 100, 80, 40);
      [self.view addSubview:btn];
    

    Here is the button action method

     -(void)btnAction
     {
       NSLog(@"button clicked");
     }
    
  11. UIButton *btnname = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    [btnname setTitle:@"Click Me" forState:UIControlStateNormal];
    
    btnname.frame = CGRectMake(10, 10, 100, 140);
    
    [self.view addSubview:btnname];
    
  12. John Riselvato on November 30, -0001 @ 12:00 AM

    Come on, it’s 2014! Why isn’t code block evaluation assignment being used yet, as trends show it’s the future!

    UIButton* button = ({
        //initialize button with frame
        UIButton* button = [[UIButton alloc] initWithFrame:({
            CGRect frame = CGRectMake(10.0, 10.0, 200.0, 75.0);
            frame;
        })];
        //set button background color
        [button setBackgroundColor:({
            UIColor* color = [UIColor colorWithRed:1.0 green:1.0 blue:0.0 alpha:1.0];
            color;
        })];
        //set button title for state
        [button setTitle:({
            NSString* string = [NSString stringWithFormat:@"title words"];
            string;
        }) forState:({
            UIControlState state = UIControlStateNormal;
            state;
        })];
        //set selector
        [button addTarget:self action:({
            SEL select = @selector(method:);
            select;
        }) forControlEvents:({
            UIControlEvents event = UIControlEventTouchUpInside;
            event;
        })];
        //return button
        button;
    });
    [self.view addSubview:button];
    

    whoa! whoa!

    Or the exact results can be accomplished as such:

    UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(10.0, 10.0, 200.0, 75.0)];
    [button setBackgroundColor:[UIColor colorWithRed:1.0 green:1.0 blue:0.0 alpha:1.0]];
    [button setTitle:@"title words" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(method:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    

    Now ask yourself, are trends really good to follow?


    This was originally posted on my blog here

  13. Darshan Kunjadiya on November 30, -0001 @ 12:00 AM

    check this code

            CGRect frameimg = CGRectMake(15, 46, 55,70);
            UIButton  *SelectionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            SelectionButton.frame=frameimg;
            SelectionButton.tag=i;
            [SelectionButton setTitle:[SelectionArray objectAtIndex:0] forState:UIControlStateNormal];
            [SelectionButton addTarget:self action:@selector(BtnSelected:)
                      forControlEvents:UIControlEventTouchUpInside];
            [SelectionButton.titleLabel setFont:[UIFont boldSystemFontOfSize:12.0]];
            SelectionButton.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
            SelectionButton.titleLabel.numberOfLines = 2;
            SelectionButton.titleLabel.textAlignment = NSTextAlignmentCenter;
            [SelectionButton setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
            [SelectionButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
            [SelectionButton setShowsTouchWhenHighlighted:YES];
            [self.view addSubview:SelectionButton];
    

    i hope this code useful for you.

  14. UIButton *custombutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [custombutton addTarget:self
                     action:@selector(aMethod:)
           forControlEvents:UIControlEventTouchUpInside];
    [custombutton setTitle:@"Click" forState:UIControlStateNormal];
    custombutton.frame = CGRectMake(80.0, 110.0, 160.0, 40.0);
    custombutton.titleLabel.textColor = [UIColor colorWithRed: 2.0f/255.0f green: 155.0f/255.0f blue: 213.0f/255.0f  alpha:1];
     [custombutton setImage:[UIImage imageNamed:@"hh.png"] forState:UIControlStateNormal];
     [view addSubview:custombutton];
    
  15. use this code wherever you needed

    UIButton *buttonName = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [buttonName addTarget:self 
           action:@selector(aMethod:)forControlEvents:UIControlEventTouchDown];
    [buttonName setTitle:@"Show View" forState:UIControlStateNormal];
    buttonName.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    [view addSubview:buttonName];
    
  16. This is an example as well to create three buttons. Just move their location.

    UIImage *buttonOff = [UIImage imageNamed:@"crysBallNorm.png"];
    UIImage *buttonOn = [UIImage imageNamed:@"crysBallHigh.png"];
    
    UIButton *predictButton = [UIButton alloc];
    predictButton = [UIButton buttonWithType:UIButtonTypeCustom];
    predictButton.frame = CGRectMake(180.0, 510.0, 120.0, 30.0);
    [predictButton setBackgroundImage:buttonOff forState:UIControlStateNormal];
    [predictButton setBackgroundImage:buttonOn forState:UIControlStateHighlighted];
    [predictButton setTitle:@"Predict" forState:UIControlStateNormal];
    [predictButton setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
    [predictButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:predictButton];
    
  17. 'action:@selector(aMethod:)' write method like this :

    - (void)aMethod:(UIButton*)button
       {
             NSLog(@"Button  clicked.");
      }
    

    It works for me. Thanks. KS.

  18. try this code to create a button and repeat it for 2 more times with different coordinates and the method(myButtonClick) is called when the button is pressed

    UIButton *editButton = [UIButton buttonWithType: UIButtonTypeCustom];
    editButton.frame = CGRectMake(0, 0, width, height);
    [editButton setBackgroundImage: editButtonImage forState: UIControlStateNormal];
    [myButton addTarget:self action:@selector(myButtonClick:)    forControlEvents:UIControlEventTouchUpInside]; 
    editButton.adjustsImageWhenHighlighted = YES;
    editButton.titleLabel.text = @"Edit";
    editButton.titleLabel.textColor = [UIColor whiteColor];
    editButton.titleLabel.textAlignment = UITextAlignmentCenter;
    editButton.titleLabel.font = [UIFont fontWithName: @"Helvetica" size: 14];
    [self.view addSubview: editButton];
    
    -(void) myButtonClick:(NSString *)myString{
    
       NSLog(@"you clicked on button %@", myString);
    }
    
  19. -(UIButton *)addButton:(NSString *)title :(CGRect)frame : (SEL)selector :(UIImage *)image :(int)tag{
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setImage:image forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor clearColor];
    btn.tag = tag;
    
    return btn;
    
    }
    

    and you can add it to the view:

    [self.view addSubview:[self addButton:nil :self.view.frame :@selector(btnAction:) :[UIImage imageNamed:@"img.png"] :1]];
    
  20. UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self 
           action:@selector(aMethod:)
     forControlEvents:UIControlEventTouchDown];
    [button setTitle:@"Show View" forState:UIControlStateNormal];
    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
    [view addSubview:button];
    
  21. Chirag Pipaliya on November 30, -0001 @ 12:00 AM

    Try it….

    UIButton *finalPriceBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    finalPriceBtn.frame=CGRectMake(260, 25, 45, 15);
    [finalPriceBtn addTarget:self action:@selector(goBtnClk:) forControlEvents:UIControlEventTouchUpInside];
    finalPriceBtn.titleLabel.font=[UIFont systemFontOfSize:12];
    [finalPriceBtn setTitle:[NSString stringWithFormat:@"$%.2f",tempVal] forState:UIControlStateNormal];
    finalPriceBtn.titleLabel.textColor = [UIColor colorWithRed: 2.0f/255.0f green: 155.0f/255.0f blue: 213.0f/255.0f  alpha:1];
    finalPriceBtn.titleLabel.textAlignment=UITextAlignmentLeft;
    [imageView addSubview:finalPriceBtn];
    

    Hope i helped.

  22. himanshu padia on November 30, -0001 @ 12:00 AM
    // Create the Button with RoundedRect type
    
    UIButton *mybutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    // instend of "Click Me" you can write your own message/Label
    
    [mybutton setTitle:@"Click Me" forState:UIControlStateNormal];
    
    // create the Rectangle Frame with specified size
    
    mybutton.frame = CGRectMake(10, 10, 300, 140); // x,y,width,height
    
    [self.view addSubview:mybutton];// add button to your view.
    
  23. UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self 
               action:@selector(aMethod:)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Show View" forState:UIControlStateNormal];
    button.frame = CGRectMake(10.0, 100.0, 300.0, 20.0);
    [self.view addSubview:button];
    
  24. Here you can create dynamically a UIButton:

    //For button image
    UIImage *closebtnimg = [UIImage imageNamed:@"close_btn.png"];
    //Custom type button
    btnclose = [[UIButton buttonWithType:UIButtonTypeCustom]retain];
    //Set frame of button means position
    btnclose.frame = CGRectMake(103, 257, 94, 32);
    //Button with 0 border so it's shape like image shape
    [btnclose.layer setBorderWidth:0];
    //Set title of button
    [btnclose setTitle:@"CLOSE" forState:UIControlStateNormal];
    [btnclose addTarget:self action:@selector(methodname:) forControlEvents:UIControlEventTouchUpInside];
    //Font size of title
    btnclose.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    //Set image of button
    [btnclose setBackgroundImage:closebtnimg forState:UIControlStateNormal];
    
  25. - (void)viewDidLoad {
        [super viewDidLoad];
        [self addMyButton];   // Call add button method on view load
    }
    
    - (void)addMyButton{    // Method for creating button, with background image and other properties
    
        UIButton *playButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
        playButton.frame = CGRectMake(110.0, 360.0, 100.0, 30.0);
        [playButton setTitle:@"Play" forState:UIControlStateNormal];
        playButton.backgroundColor = [UIColor clearColor];
        [playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
        UIImage *buttonImageNormal = [UIImage imageNamed:@"blueButton.png"];
        UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
        [playButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
        UIImage *buttonImagePressed = [UIImage imageNamed:@"whiteButton.png"];
        UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
        [playButton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
        [playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:playButton];  
    }
    
  26. To add a button programatically to your controller’s view, use the following:

    -(void)viewDidLoad
    {
       UIButton * btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
       btn.frame = CGRectMake(0, 0, 100, 50);
       [btn setTitle:@"Hello, world!" forState:UIControlStateNormal];
       [self.view addSubview:btn];
    }
    

    To add three of these, rinse and repeat.

Leave a Reply