Make part of a UILabel bold in Swift

后端 未结 9 1969
面向向阳花
面向向阳花 2020-12-02 12:50

I have a UILabel I\'ve made programmatically as:

var label = UILabel()

I\'ve then declared some styling for the label, includi

9条回答
  •  死守一世寂寞
    2020-12-02 13:33

    You can directly do on String if you prefer:

    extension String {
    func withBoldText(text: String, font: UIFont? = nil) -> NSAttributedString {
      let _font = font ?? UIFont.systemFont(ofSize: 14, weight: .regular)
      let fullString = NSMutableAttributedString(string: self, attributes: [NSAttributedString.Key.font: _font])
      let boldFontAttribute: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: _font.pointSize)]
      let range = (self as NSString).range(of: text)
      fullString.addAttributes(boldFontAttribute, range: range)
      return fullString
    }}
    

    Usage:

    label.attributeString = "my full string".withBoldText(text: "full")
    

提交回复
热议问题