12

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

4

6 回答 6

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];   

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

于 2009-06-26T04:49:26.220 回答
22

问题在于

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

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

单独设置它的框架:

b.frame = CGRectMake(0, 0, 100, 100);
于 2009-06-26T05:02:16.890 回答
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];  
于 2009-06-26T04:53:05.187 回答
0

问题是你必须使用[[UIButton alloc] initWithFrame:]or [UIButton buttonWithType:],你不应该同时使用两者。

于 2012-07-31T19:11:28.183 回答
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];
于 2013-03-05T10:55:00.047 回答
0

我遇到了同样的问题,结果是我设置的是图像而不是背景图像。当我这样做时,一切都很好:

[button setBackgroundImage:image forState:UIControlStateNormal];
于 2013-06-26T12:58:22.917 回答