[英]Set Button title in two different colors in iOS
I want to set title on Button in two colors. 我想在Button上设置两种颜色的标题。
Is it possible same as given image below ? 它可能与下面给出的图像相同吗?
Any help will be appreciated. 任何帮助将不胜感激。
Thanks in advance. 提前致谢。
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];
In storyBoard : Follow the ScreenShot. 在storyBoard中:关注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 对于编程:这里已经有很多答案帖子在这里为属性文本和如果你想为UIButton 设置 BackgroundImage 设置一个按钮背景图像iPhone以编程方式
For swift 3: 对于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)
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];
[button setAttributedTitle:someAttributedText forState:UIControlStateNormal];
您可以使用低于5.0的ios和当前ios版本的NSMutableAttributedString
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.