UILable添加着重标记

用途:

 在UILable展示时,在任意地方添加一个标记(比如:*),作为特殊标题的记号(如:必填项等)

代码

 extension UILabel {
  // 放置符号
  enum EmphasisText: String {
    case star = "*"
  }
  // 放置位置
  enum EmphasisPosition {
    case start
    case index(Int)
    case end
  }

  func setupAttr(_ emphasis: EmphasisText, color: UIColor? = UIColor.red, position: EmphasisPosition? = .start) {
    if let str = self.text, str.count > 0 {
        var string = ""
        switch position! {
        case .start:
            string = emphasis.rawValue + str
        case .index(let i):
            string = str
            string.insert(contentsOf: emphasis.rawValue, at: str.index(str.startIndex, offsetBy: i))
        case .end:
            string = str + emphasis.rawValue
        }
        
        let ranStr = emphasis.rawValue
        let attrStr: NSMutableAttributedString = NSMutableAttributedString(string:string)
        let strN = NSString(string: string)
        let range = strN.range(of: ranStr)
        attrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: color!, range: range)
        
        self.text = ""
        self.attributedText = attrStr
        }
    }
}

你可能感兴趣的:(UILable添加着重标记)