Search code examples
iosuibuttonviewdidload

ios - Programmatically coded UIButton not showing on my view


.

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


Solution

  • 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.