淘先锋技术网

首页 1 2 3 4 5 6 7
extension String {
    /// range转换为NSRange
    func nsRange(from range: Range<String.Index>) -> NSRange {
        return NSRange(range, in: self)
    }
}
  • 使用代码
        let labelText = label.text!
        let range:Range = labelText.range(of: "高度")!

        let nsrange = labelText.nsRange(from: range)

        let mutableAttribute = NSMutableAttributedString(attributedString: label.attributedText!)
        mutableAttribute.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.red, NSAttributedString.Key.font : UIFont.init(name: "PingFang SC", size: 14)!], range: nsrange)
        label.attributedText = mutableAttribute

参考博客:
Swift4 range与NSRange互转,字符串查找

我的另外一篇相关博客:
iOS swift5 改变UILabel上指定文字的颜色和字体