繁体   English   中英

在iOS中以两种不同的颜色设置Button标题

[英]Set Button title in two different colors in iOS

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

它可能与下面给出的图像相同吗?

按钮有2种颜色

任何帮助将不胜感激。

提前致谢。

这就是你需要的

  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中:关注ScreenShot。

在此输入图像描述

在此输入图像描述

在此输入图像描述

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

对于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)

试试这个

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM