我想在按钮上设置两种颜色的标题。
是否可能与下面给出的图像相同?
任何帮助将不胜感激。
提前致谢。
这就是你需要的
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];
在 storyBoard 中:按照屏幕截图。
以编程方式:这里已经有很多关于属性文本的答案帖子,如果你想为 UIButton 放置 BackgroundImage 以编程方式 设置按钮背景图像 iPhone
对于迅捷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)
尝试这个
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];
您可以用于 5.0 以下的 ios
和NSMutableAttributedString
当前的 ios 版本。
[button setAttributedTitle:someAttributedText forState:UIControlStateNormal];