繁体   English   中英

iOS:UIButton不显示

[英]iOS: UIButton doesn't show 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);

您可能已经注意到,我在最后放置了一些调试代码,以查看按钮的位置和尺寸。 它们是:X:0,Y:0,宽度:30,高度:34

这意味着它应该显示在左上角,但不是。 怎么了?

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

UIButton* contactButton = [UIButton buttonWithType:UIButtonTypeCustom];

尝试以其他方式构造按钮:

UIButton* contactButton = [UIButton buttonWithType:UIButtonTypeCustom];
contactButton.backgroundColor = [UIColor redColor];
contactButton.titleLabel.text = @"Contact Developer";
[contactButton sizeToFit];
[self.view addSubview:contactButton];

一种可能的原因是您直接使用了titleLabel 考虑改用setTitle:forState:方法。

可以肯定的是,请考虑将backgroundColor设置为调试步骤,以确保它出现了。


编辑其他建议,请尝试使用buttonWithType:而不是[[UIButton alloc] init] 我建议使用UIButtonTypeSystem而不是UIButtonTypeCustom

您确定按钮没有显示吗?

我认为您未正确设置按钮的标题,并且由于默认UIButton具有清晰的背景和白色标题,因此如果您的超级视图也为白色,则该按钮不可见。
而不是设置:
contactButton.titleLabel.text = @"Contact Developer"
采用:
[contactButton setTitle:@"Contact Developer" forState:UIControlStateNormal]

但是,您可以首先尝试将按钮的backgroundColor设置为与超级视图不同的按钮,以查看是否添加了该按钮。

希望能帮助到你!
(对不起,如果我输入错误,我的英语)

暂无
暂无

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

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