Reputation: 2745
I want to set title on Button in two colors.
Is it possible same as given image below ?
Any help will be appreciated.
Thanks in advance.
Upvotes: 5
Views: 8115
Reputation: 6570
This is what you need
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(5,10,300,20);
[self.view addSubview:btn];
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"100 Photos"]];
[attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 3)];
[btn setAttributedTitle:attrStr forState:UIControlStateNormal];
Upvotes: 15
Reputation: 5772
For swift 3:
let button = UIButton()
let mainTitle = "200"
let subtitle = "Members"
let attrText1 = NSMutableAttributedString(string: mainTitle)
attrText1.addAttribute(NSFontAttributeName, value: 15, range: NSMakeRange(0, attrText1.length))
attrText1.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range: NSMakeRange(0, attrText1.length))
let attrText2 = NSMutableAttributedString(string: subtitle)
attrText2.addAttribute(NSFontAttributeName, value: 15, range: NSMakeRange(0, attrText2.length))
attrText2.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellow, range: NSMakeRange(0, attrText2.length))
let attributedText = NSMutableAttributedString()
attributedText.append(attrText1)
attributedText.append(attrText2)
//Center align
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
attributedText.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0,attributedText.length))
button.setAttributedTitle(attributedText, for: .normal)
Upvotes: 3
Reputation: 39
you can use for ios below 5.0
and NSMutableAttributedString
for current ios versions.
Upvotes: 0
Reputation: 15335
In storyBoard : Follow the ScreenShot.
For Programmatically : There are already many answers posts over here for attributed text and If you want to put BackgroundImage for UIButton Set a button background image iPhone programmatically
Upvotes: 13
Reputation: 20021
Try this
NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc] initWithString:@"ThisIsAttributed"];
[mutableString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,4)];
[mutableString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(5,2)];
[button setAttributedTitle:mutableString forState:UIControlStateNormal];
Upvotes: 2
Reputation: 1505
[button setAttributedTitle:someAttributedText forState:UIControlStateNormal];
Upvotes: 0