简体   繁体   中英

iOS: UIButton doesn't show up

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?

您应该使用以下方法初始化按钮:

UIButton* contactButton = [UIButton buttonWithType:UIButtonTypeCustom];

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];

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM