Swift4 UILabel AttributedString 检索字符串分段改变颜色

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

String扩展类方法

func nsRange(from range: Range) -> NSRange? {

        let utf16view = self.utf16

    if let from = range.lowerBound.samePosition(in: utf16view), let to = range.upperBound.samePosition(in: utf16view) {

            return NSMakeRange(utf16view.distance(from: utf16view.startIndex, to: from), utf16view.distance(from: from, to: to))

        }

        return nil

    }

使用:

let text = "检索字符串"

                let attributedString = NSMutableAttributedString(string: text)

                let range = attributedString.string.range(of: "字符")

                let nsrange = attributedString.string.nsRange(from: range!)

                attributedString.addAttribute(.foregroundColor, value: UIColor.red, range: nsrange!)

                label.attributedText = attributedString

转载于:https://my.oschina.net/u/3382458/blog/1613631

你可能感兴趣的:(Swift4 UILabel AttributedString 检索字符串分段改变颜色)