AttributedText + Regex Swift 4.2


This example of how to combine attribute text and regex for change color and underline, you would like to match but quickly fetch only word.



Now with regular expressions,  and how to use it :


import UIKit



class AtttibuteStringUniqueVC: UIViewController {

    @IBOutlet weak var amountTexfield: UITextField!

    @IBOutlet weak var attribute: UILabel!

    

    override func viewDidLoad() {

        super.viewDidLoad()

    }

    

    @IBAction func handleShow(_ sender: Any) {

        attribute.attributedText = attrText("$ \(amountTexfield.text ?? "")*")

    }

    

    func attrText(_ inString: String) -> NSAttributedString {

        let pattern = "\\.(.*?\\*)"

        let regex = try? NSRegularExpression(pattern: pattern, options: [])

        let range = NSMakeRange(0, inString.count)

        let matches = (regex?.matches(in: inString, options: [], range: range))!

        

        let attrString = NSMutableAttributedString(string: inString, attributes: [

            .font: UIFont.systemFont(ofSize: 36.0, weight: .semibold),

            .foregroundColor:  colorLiteral(red: 0.1294117647, green: 0.1294117647, blue: 0.1294117647, alpha: 1),

            .kern: 0.43

        ])

        

        // Iterate over regex matches

        for match in matches.reversed() {

            // Properly print match range

            print(match.range)

            

            let underlineAttribute = [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue]

            

            if inString.count <= 11 {

                attrString.addAttribute(.foregroundColor, value: UIColor(red: 245.0 / 255.0, green: 166.0 / 255.0, blue: 35.0 / 255.0, alpha: 1.0), range: NSRange(location: match.range(at: 1).location, length: 4))

                attrString.addAttributes(underlineAttribute, range: NSRange(location: match.range(at: 1).location, length: 3))

                

            } else {

                attrString.addAttribute(.foregroundColor, value: UIColor(red: 245.0 / 255.0, green: 166.0 / 255.0, blue: 35.0 / 255.0, alpha: 1.0), range: NSRange(location: match.range(at: 1).location + 4, length: 4))

                attrString.addAttributes(underlineAttribute, range: NSRange(location: match.range(at: 1).location + 4, length: 3))

            }

        }

        return attrString

    }

}

thanks for https://stackoverflow.com/a/27067740/8366535



No comments: