是否可以在Swift上的UIButton中添加两个标签?

时间:2016-09-06 10:12:08

标签: ios swift uibutton

我的UIButton项目中有一个Swift,我想使用一个字体很棒的图标,里面有文字。

我知道我可以为按钮设置标题但是,到目前为止我需要图标和文本使用不同的文本大小,我不能将它们组合在同一标题标签中。我也考虑过使用带有属性标题的图像(设置字体 - 真棒图标)但我无法改变字体 - 真棒图标的颜色。

我知道我可以在UIView中添加两个标签,但我想知道是否可以在UIButton上添加此标签。

提前致谢!

1 个答案:

答案 0 :(得分:3)

您可以使用属性字符串设置按钮的属性标题,例如

 let attributedTitle = NSAttributedString(string: "Click Here",
attributes: [NSForegroundColorAttributeName : UIColor.blueColor()])
button.setAttributedTitle(attributedTitle, forState: .Normal)

您可以为特定文本或字符串的一部分设置多种颜色,字体,大小。

另一个例子,

 attributedTitle = NSMutableAttributedString(string: @"Click Here", attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])

   attributedTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))

  button.setAttributedTitle(attributedTitle, forState: .Normal)

因此,您可以使用NSRange指定位置,并可以为指定范围设置不同的颜色和字体属性!

相关问题