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

相關文章
相關標籤/搜索