Swift4 UILabel AttributedString retrieves the string segmented to change the color

String extension class method

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

    }

use:

let text = "Retrieve String"

                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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325452090&siteId=291194637