The label on UIButton of type UIButtonTypeCustom is not displayed

advertisements

I want to add a borderless UIButton to my view. Using the interface builder, I do this by dragging a Round Rect Button from the object library. Then, on the attributes inspector, change the Type to Custom and leave the title to "Button." Everything is okay with the interface builder. But, this is not the case with the programmatic approach. Programmatically, this is how I do it:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(x, y, width, height)];
[button setTitle:@"Button" forState:UIControlStateNormal];

When I run the app, the button is not displayed. Maybe I'm missing something here but when I change the type to UIButtonTypeRoundRect the button is displayed. But, again, I want the button to be borderless.

Anyway, I can always use the interface builder. However, I want to understand why the programmatic approach doesn't work. So, does anyone know what the problem is?


UIButtonTypeCustom is really, actually a custom button type. There are no meaningful values setup for it by default. If you want to display it, you have to set its background color and/or its title color to a non-transparent one:

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(x, y, width, height)];
[button setTitle:@"Button" forState:UIControlStateNormal];
// Set visible values
[button setBackgroundColor:[UIColor greenColor]];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[someSuperview addSubview:button];