ios - Programmatically coded UIButton not showing on my view

16,901

Solution 1

I think you may be inserting the button correctly, but just can't see it because it has no background and the text isn't showing.

Try using a rounded rect button system button, just to see if that makes it show up. Set the text correctly. I'll also remove setting the font, just incase there's a problem with the font.

// backButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
backButton = [UIButton buttonWithType:UIButtonTypeSystem];
backButton.frame = CGRectMake(10, 25, 150, 75);
[backButton setTitle:@"Back" forState:UIControlStateNormal];
[self.view addSubview:backButton];

Update: UIButtonTypeRoundedRect has beed deprecated.

Solution 2

You have created button using static method buttonWithType ,Again you have allocated memory for that button.

UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
backButton.frame = CGRectMake(10, 25, 150, 75);
backButton.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
backButton.titleLabel.text = @"Back";
[self.view addSubview:backButton];

Solution 3

You are setting the button title incorrectly. Use:

- (void)setTitle:(NSString *)title forState:(UIControlState)state

Also as others have said you don't need to initialize your button three times. Remove the 2nd and 3rd lines.

Share:
16,901
jwknz
Author by

jwknz

Hi, Working as a CS Tutor and enjoying full stack development in my day-to-day coding. Cheers, Jeff

Updated on July 26, 2022

Comments

  • jwknz
    jwknz almost 2 years

    .

    Hello,

    I am trying to add a UIButton and other items to my UIViewController programmatically and from what I have read and seen in other SO questions I should be on the right track with this code:

    - (void)viewDidLoad
    {
    [super viewDidLoad];
    
    
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];    
    backButton = [[UIButton alloc] init];
    backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(10, 25, 150, 75);
    backButton.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15];
    backButton.titleLabel.text = @"Back"; 
    [self.view addSubview:backButton];
    
    
    // Do any additional setup after loading the view.
    }
    

    Now that code is placed in the viewDidLoad Method and it does not appear, which leads me to the question - What am I doing wrong?

    When I want to change the color of the background and put in the viewDidLoad it works fine.

    Cheers Jeff