Reputation: 43
I would like create a button with two independent labels. I want to set in one button, two separate texts in different colors. e.g.
[myButton setTitle: @"Title" forState: UIControlStateNormal];
[myButton setTitle2: @"Title2" forState: UIControlStateNormal];
Is it even possible? Maybe I should need to create a new control? Can anyone help me? I will be very grateful for a tutorial step by step.
Upvotes: 4
Views: 6430
Reputation: 1976
Swift Version:
The following code also centres two titles both horizontally and vertically inside the button and has some font style adjustments.
let lineOne = UILabel.init(frame: CGRect(x: 0, y: self.button.frame.size.height / 4, width: self.button.frame.size.width, height: self.button.frame.size.height / 4))
lineOne.text = "Title 1"
lineOne.textColor = .black
lineOne.font = UIFont.boldSystemFont(ofSize: 13.0)
lineOne.textAlignment = .center
let lineTwo = UILabel.init(frame: CGRect(x: 0, y: lineOne.frame.size.height * 2, width: self.button.frame.size.width, height: self.button.frame.size.height / 4))
lineTwo.text = "Title 2"
lineTwo.textColor = .black
lineTwo.font = UIFont.boldSystemFont(ofSize: 13)
lineTwo.textAlignment = .center
self.button.addSubview(lineOne)
self.button.insertSubview(lineTwo, belowSubview: lineOne)
Upvotes: 1
Reputation: 194
If you wanted to do it all in Interface Builder you could place two UILabels where you want them in the view and then lay a UIButton over the top of them. Then with the Attributes Inspector change the UIButton's type to "Custom" and delete any existing label or placeholder text it has. This will make the button clear so both labels show through and you can set the UIButton's IBAction to do whatever you want to the two separate UILabels.
Upvotes: 4
Reputation: 4187
Also, you can do this :
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeCustom];
testButton.frame = CGRectMake(0, 0, 200, 40);
[self.view addSubview:testButton];
UILabel *firstLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
firstLineTestButton.text = @"First line";
firstLineTestButton.font = [UIFont systemFontOfSize:12];
[testButton addSubview:firstLineTestButton];
UILabel *secondLineTestButton = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 200, 20)];
secondLineTestButton.text = @"Second line";
secondLineTestButton.font = [UIFont boldSystemFontOfSize:12];
[testButton addSubview:secondLineTestButton];
but the @vikingosegundo's solution is more appropriate for the new SDK
Upvotes: 3
Reputation: 52227
For iOS 6 and higher you can use setAttributedTitle:forState:
to set an attributes string. A NSAttributedString can have many different attributes like text color.
Upvotes: 2
Reputation: 1784
UIButton
is a subclass of UIView
. So you can add two different labels to your button using - (void)addSubview:(UIView *)view
. Positioning could then be done either with Autolayout (if you are using that), or frames + springs/struts.
Upvotes: 0