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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With