5

我想在按钮上设置两种颜色的标题。

是否可能与下面给出的图像相同?

2种颜色的按钮

任何帮助将不胜感激。

提前致谢。

4

6 回答 6

15

这就是你需要的

  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];
于 2013-06-27T10:26:07.543 回答
13

在 storyBoard 中:按照屏幕截图。

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

以编程方式:这里已经有很多关于属性文本的答案帖子,如果你想为 UIButton 放置 BackgroundImage 以编程方式 设置按钮背景图像 iPhone

于 2013-06-27T10:20:17.160 回答
3

对于迅捷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)
于 2017-02-15T18:04:48.397 回答
2

尝试这个

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];
于 2013-06-27T10:21:29.540 回答
0

您可以用于 5.0 以下的 iosNSMutableAttributedString当前的 ios 版本。

于 2013-06-27T12:27:58.807 回答
0
[button setAttributedTitle:someAttributedText forState:UIControlStateNormal];
于 2013-06-27T10:18:41.853 回答