简体   繁体   English

iOS:UIButton不显示

[英]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 它们是:X:0,Y:0,宽度:30,高度: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. 一种可能的原因是您直接使用了titleLabel Consider using setTitle:forState: method instead. 考虑改用setTitle:forState:方法。

To be sure, consider setting backgroundColor , as a debug step, to make sure it's appearing. 可以肯定的是,请考虑将backgroundColor设置为调试步骤,以确保它出现了。


Edit As others suggested, try using buttonWithType: instead of [[UIButton alloc] init] . 编辑其他建议,请尝试使用buttonWithType:而不是[[UIButton alloc] init] I suggest using UIButtonTypeSystem instead of UIButtonTypeCustom . 我建议使用UIButtonTypeSystem而不是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. 我认为您未正确设置按钮的标题,并且由于默认UIButton具有清晰的背景和白色标题,因此如果您的超级视图也为白色,则该按钮不可见。
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. 但是,您可以首先尝试将按钮的backgroundColor设置为与超级视图不同的按钮,以查看是否添加了该按钮。

Hope it helps! 希望能帮助到你!
(Sorry for my english if i have a mistake) (对不起,如果我输入错误,我的英语)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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