Swift:使用setTitleTextAttributes为范围设置粗体

时间:2016-03-04 15:45:55

标签: swift uibarbuttonitem

如何创建如下按钮:

[数: 1]

其中Count:为粗体,1为纯文本。

let range = NSMakeRange(0,7)
let attrs = [NSFontAttributeName:UIFont.boldSystemFontOfSize(12)]
leftNameButton.setTitleTextAttributes(attrs, forState: UIControlState.Normal)
 // Where does range go?

2 个答案:

答案 0 :(得分:1)

如果您希望这可以在UIBarButtonItem上运行,您需要像这样使用customView:

let yourString = NSMutableAttributedString(string: "Count: 1")
yourString.setAttributes(attrs, range: range)
let buttonLabel = UILabel()
buttonLabel.attributedText = yourString
buttonLabel.sizeToFit() // Important for bar buttons
let barButton = UIBarButtonItem(customView: buttonLabel)

答案 1 :(得分:-1)

您需要使用NSMutableAttributedString

let yourString = NSMutableAttributedString(string: "[Count:1]",attributes: attrs!])

yourString.addAttribute(attrs!, range: range)

yourButton.text = yourString