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

String扩展类方法

func nsRange(from range: Range<String.Index>) -> 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

猜你喜欢

转载自my.oschina.net/u/3382458/blog/1613631