在UIViewController的viewDidLoad方法中,我这样做:

UIButton *b = [[UIButton buttonWithType:UIButtonTypeRoundedRect]
                                       initWithFrame:CGRectMake(0, 0, 100, 100)];

[b setTitle:@"Testing" forState:UIControlStateNormal];
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
[self.view addSubview:b];                       // EDIT: should be 'b'
NSLog(@"button title: %@", [b titleLabel].text);


该按钮显示,但标题不显示。 NSLog行将“ Testing”打印到控制台。关于我在做什么错的任何建议吗?

最佳答案

我无法告诉您为什么它不起作用,但是我有一个解决方案:

UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect] ;
b. frame = CGRectMake(0, 0, 100, 100);

[b setTitle:@"Testing" forState:UIControlStateNormal];
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
[self addSubview:b];


将创建框架与按钮的分配和初始化分开。

07-26 09:37