views:

4223

answers:

5

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?

A: 

According to the example above, you instantiate a UIButton called "b" but then add a subview to self.view called "button."

bpapa
Sorry - that was a typo. I've corrected it.
4thSpace
A: 

Two ideas:

  • What happens if you make your button larger?
  • Are you doing anything else in viewDidLoad that could be affecting the button?
JonathonW
+6  A: 

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.

Paxic
I agree. I bet chaining two initializers together like you're doing is causing some issues. Use the buttonWithType then set the frame.
LucasTizma
+1  A: 

Do this instead:

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];
Marco Mustapic
+6  A: 

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