swift 将字符串与颜色字体和其他字符串归

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 将字符串与颜色字体和其他字符串归相关的知识,希望对你有一定的参考价值。

import Foundation
import UIKit

let defaultFont = UIFont.systemFont(ofSize: 15)

extension NSMutableAttributedString {
  @discardableResult func bold(_ text: String, font: UIFont = defaultFont) -> NSMutableAttributedString {
    let attrs: [NSAttributedString.Key: Any] = [
      .font: font
    ]
    let boldString = NSMutableAttributedString(string:text, attributes: attrs)
    append(boldString)
    
    return self
  }
  @discardableResult func bold(_ text: String, color: UIColor, font: UIFont = defaultFont) -> NSMutableAttributedString {
    let attrs: [NSAttributedString.Key: Any] = [
      .font: font,
      .foregroundColor: color
    ]
    let boldString = NSMutableAttributedString(string:text, attributes: attrs)
    append(boldString)
    
    return self
  }
  
  @discardableResult func normal(_ text: String, color: UIColor = .black, alignment: NSTextAlignment = .left, font: UIFont = defaultFont) -> NSMutableAttributedString {
    
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = alignment
    
    let attrs: [NSAttributedString.Key: Any] = [
      .foregroundColor: color,
      .font: font,
      .paragraphStyle: paragraphStyle
    ]
    let string = NSMutableAttributedString(string:text, attributes: attrs)
    append(string)
    
    return self
  }
  
  @discardableResult func normal(_ text: String, font: UIFont = defaultFont) -> NSMutableAttributedString {
    let attrs: [NSAttributedString.Key: Any] = [
      .font: font
    ]
    let string = NSMutableAttributedString(string:text, attributes: attrs)
    append(string)
    
    return self
  }
  
  @discardableResult func append(_ text: String, withAttributes attributes: [NSAttributedString.Key: Any]) -> NSMutableAttributedString {
    let attributedString = NSMutableAttributedString(string:text, attributes: attributes)
    append(attributedString)
    
    return self
  }
}
let formattedString = NSMutableAttributedString()
    formattedString
      .normal(message)
      .bold(formattedPrice, color: UIColor.tele2AlertGreen)

以上是关于swift 将字符串与颜色字体和其他字符串归的主要内容,如果未能解决你的问题,请参考以下文章

Swift - UILabel部分字体变颜色

Swift - UILabel部分字体变颜色

ios swift:是不是可以更改字符串中某个单词的字体样式?

具有不同字体大小和颜色的UILabel文本[重复]

在 iOS8/Swift 中为 UIDatePicker 设置文本颜色和字体

编写html中如何将中间某一个字符改变字体颜色?