【问题标题】:Is it possible to add two labels inside an UIButton on Swift?是否可以在 Swift 的 UIButton 内添加两个标签?
【发布时间】:2016-09-06 10:12:07
【问题描述】:

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

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

我知道我可以在 UIView 中添加两个标签来获得这种行为,但我想知道是否可以在 UIButton 上获得这种行为。

提前致谢!

【问题讨论】:

  • 你试过setAttributedTitle 属性字符串吗?
  • @KetanParmar 属性字符串是什么意思?
  • NSAttributedString 在一个字符串中可以有不同的大小/文本/字体/颜色,请尝试搜索如何创建它
  • @Tj3n 好的,谢谢,我现在要搜索它:)

标签: ios swift uibutton


【解决方案1】:

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

 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 指定位置,并可以为指定范围设置不同的颜色和字体属性!

【讨论】:

  • 非常感谢!这就是我一直在寻找的。​​span>
猜你喜欢
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多