Reputation: 846
I want to add a UILabel
within a UIButton
.
Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
[[self addressSearch] setDelegate:self];
[[self worldMap] setDelegate:self];
self.boolPushButtonTapped = YES;
self.addressSearch.barStyle = 1;
//Create pushButton
self.pushButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.pushButton.frame = CGRectMake(106, 436, 110, 59);
[self.pushButton setBackgroundImage:[UIImage imageNamed:@"pushButton2.png"] forState:UIControlStateNormal];
[self.pushButton addTarget:self action:@selector(pushButtonTapped) forControlEvents:UIControlEventTouchUpInside];
//Label
self.distanceLabel = [[UILabel alloc] init];
self.distanceLabel.text = @"test";
[self.pushButton addSubview:self.distanceLabel];
[self.view addSubview:self.pushButton];
}
If I don't use alloc
init
I receive an error and if I use the text in that label does not change.
Error:
*** Assertion failure in -[NSLayoutConstraint constant], /SourceCache/Foundation/Foundation-992/Layout.subproj/NSLayoutConstraint.m:560
2012-10-01 14:01:01.889 RemindMe[1116:907] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '(null)'
I want to add inside this button because there is an animation.
Any suggestions?
Upvotes: 4
Views: 5604
Reputation: 2814
You could try this:
[self.pushButton.titleLabel setText: @"anytext"];
Updated answer:
As mentioned in the UIButton Class Reference, you should set the title using setTitle:forState:
.
Then the formatting can be done in the button's associated label object titleLabel
.
So you need not add another UILabel.
Hope this helps!
Upvotes: 1
Reputation: 608
UIButtons now give you a lot of control, but before some things like custom fonts were possible I just made a simple control that had a UIButton and UILabel. I would just put the UILabel on top of the UIButton with a small 2px or so padding.
Upvotes: 1