Reputation: 1230
I'm creating a simple button and adding it as a subview to main view. It doesn't show up though.
This is the code for setting it up:
UIButton* contactButton = [[UIButton alloc] init];
contactButton.titleLabel.text = @"Contact Developer";
[contactButton sizeToFit];
[self.view addSubview:contactButton];
NSLog(@"X: %f || Y: %f || Width: %f || Height: %f", contactButton.frame.origin.x, contactButton.frame.origin.y, contactButton.frame.size.width, contactButton.frame.size.height);
As you may have noticed, I placed a bit of debug code at the end to see the position and dimensions of the button. They are: X: 0, Y: 0, Width: 30, Height: 34
This means it should be showing up in the upper left corner but it doesn't. Whats wrong?
Upvotes: 0
Views: 1426
Reputation: 1648
One possible reason for this is that you used titleLabel
directly. Consider using setTitle:forState:
method instead.
To be sure, consider setting backgroundColor
, as a debug step, to make sure it's appearing.
Edit As others suggested, try using buttonWithType:
instead of [[UIButton alloc] init]
. I suggest using UIButtonTypeSystem
instead of UIButtonTypeCustom
.
Upvotes: 1
Reputation: 40
Are you sure that the button it's not being shown?
I think you are setting the title of the button incorrectly and because of the fact that a default UIButton
has clear background and white title, it´s not visible if your superview is white too.
Instead of setting:
contactButton.titleLabel.text = @"Contact Developer"
use:
[contactButton setTitle:@"Contact Developer" forState:UIControlStateNormal]
But you can first try to set a backgroundColor
to the button, different that the superview, to see if it's added.
Hope it helps!
(Sorry for my english if i have a mistake)
Upvotes: 1
Reputation: 14030
Try constructing your button a different way:
UIButton* contactButton = [UIButton buttonWithType:UIButtonTypeCustom];
contactButton.backgroundColor = [UIColor redColor];
contactButton.titleLabel.text = @"Contact Developer";
[contactButton sizeToFit];
[self.view addSubview:contactButton];
Upvotes: 1
Reputation: 910
You should initialise the button using the following:
UIButton* contactButton = [UIButton buttonWithType:UIButtonTypeCustom];
Upvotes: 1