Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't UIButton title display?

In a UIViewController's viewDidLoad method, I do this:

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

The button displays but the title doesn't. The NSLog line prints "Testing" to the console. Any suggestions on what I'm doing wrong?

like image 645
4thSpace Avatar asked Jun 26 '09 04:06

4thSpace


2 Answers

I cannot tell you why it does not work, but I do have a solution:

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

Seperate creating the frame from the allocation and init of the button.

like image 187
Paxic Avatar answered Oct 21 '22 02:10

Paxic


The problem lies with

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

buttonWithType returns an autoreleased initialized object. You cannot send it an initWithFrame again as an object can only be initialized once.

Set its frame separately:

b.frame = CGRectMake(0, 0, 100, 100);
like image 28
diederikh Avatar answered Oct 21 '22 03:10

diederikh