Have half a UILabel text bold and half not?

2019-08-01 10:49发布

问题:

I want half of my UILabel's text to be bold and half to not be bold. How can I do this?

回答1:

NSAttributedString allows for specification of formatting within a string, but sadly, UIKit does not yet do anything with this. However, there are a few open-source implementations that do. Check out OHAttributedLabel.



回答2:

You can't do this easily unless you subclass UILabel and mess with the subviews. Better to use two UILabels instead. Found another thread about it here.



回答3:

UILabel has attributedText which takes a NSAttributedString which allows you to customize multiple aspects of a string including changing the font type and other attributes

  var attributedString = NSMutableAttributedString(attributedString: NSAttributedString(string: "Not Bold"))

  let boldAttrString = NSAttributedString(string: "BOLD", attributes: [NSFontAttributeName: UIFont(name: "Avenir-Medium", size: 15)!])
  attributedString.appendAttributedString(boldAttrString)
  myLabel.attributesText = attributedString