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

String扩展类方法spa

func nsRange(from range: Range<String.Index>) -> NSRange? {字符串

        let utf16view = self.utf16string

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

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

        }table

        return nil扩展

    }方法

使用:tab

let text = "检索字符串"di

                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

相关文章
相关标签/搜索