为什么不显示UIButton标题?

时间:2009-06-26 04:02:21

标签: iphone cocoa-touch uiview uiviewcontroller uibutton

在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”打印到控制台。关于我做错了什么的建议?

6 个答案:

答案 0 :(得分: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];   

从按钮的分配和初始化中单独创建帧。

答案 1 :(得分:22)

问题在于

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

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

单独设置框架:

b.frame = CGRectMake(0, 0, 100, 100);

答案 2 :(得分:4)

请改为:

UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect];
b.frame = CGRectMake(0, 0, 100, 100);
[b setTitle:@"Testing" forState:UIControlStateNormal];
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal];
[self.view addSubview:b];  

答案 3 :(得分:0)

你需要选择[[UIButton alloc] initWithFrame:][UIButton buttonWithType:],你不应该同时使用它们。

答案 4 :(得分:0)

您可以执行以下操作:

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

b=[UIButton buttonWithType:UIButtonTypeRoundedRect];

[b setTitle:@"Button Title Here" forState:UIControlStateNormal];
[b setTitleColor:[UIColor blackColor] forState: UIControlStateNormal];
[self.view addSubview:b];

答案 5 :(得分:0)

我遇到了同样的问题,最终我正在设置图像而不是backgroundImage。我做的时候一切都很好:

[button setBackgroundImage:image forState:UIControlStateNormal];