为什么不显示UIButton标题?

4th*_*ace 12 iphone cocoa-touch uibutton uiviewcontroller uiview

在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);
Run Code Online (Sandbox Code Playgroud)

按钮显示但标题不显示.NSLog行将"Testing"打印到控制台.关于我做错的任何建议?

Pax*_*xic 38

我不能告诉你为什么它不起作用,但我确实有一个解决方案:

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];   
Run Code Online (Sandbox Code Playgroud)

单独从按钮的分配和初始化创建框架.


die*_*ikh 22

问题在于

UIButton *b = [[UIButton buttonWithType:UIButtonTypeRoundedRect] 
                                       initWithFrame:CGRectMake(0, 0, 100, 100)];
Run Code Online (Sandbox Code Playgroud)

buttonWithType返回一个自动释放的初始化对象.您无法再次向其发送initWithFrame,因为对象只能初始化一次.

分别设置框架:

b.frame = CGRectMake(0, 0, 100, 100);
Run Code Online (Sandbox Code Playgroud)