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行は、コンソールに「テスト」を出力します。私が間違っていることについて何か提案はありますか?

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

私は同じ問題を抱えていましたが、backgroundImageではなく画像を設定していたという事実になりました。私がやったとき、それはすべてうまくいきました:

[button setBackgroundImage:image forState:UIControlStateNormal];
于 2013-06-26T12:58:22.917 に答える
0

問題は、[[UIButton alloc] initWithFrame:]または[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 に答える