Search code examples
iosswiftuitextviewnsmutableattributedstring

Make half of the TextView's text color Different than other 50% of the text SWIFT


I've got a large text in my UITextView and I want to make the 50% of the text's color red and the other 50% green . I've added NSMutableAttributedString in the TextView but it works's for the full range of the text . How to divide the textView's text into two sections and color them into red and green ?

let strNumber: NSString = self.text as NSString // TextView Text
        let range = (strNumber).range(of: strNumber as String)
        let attribute = NSMutableAttributedString.init(string: strNumber as String)
        attribute.addAttributes([NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14) , NSAttributedString.Key.foregroundColor : UIColor.red], range: range)
        self.attributedText = attribute

Solution

  • It seems you have an extension to UITextView. The following extension function will make the existing attributed text of a text view be half red and half green. All other existing attributes, if any, will remain.

    extension UITextView {
        func makeHalfRedGreen() {
            if let text = self.text {
                let half = text.count / 2
                let halfIndex = text.index(text.startIndex, offsetBy: half)
                let firstRange = NSRange(..<halfIndex, in: text)
                let secondRange = NSRange(halfIndex..., in: text)
                let attrTxt = NSMutableAttributedString(attributedString: attributedText)
                attrTxt.addAttribute(.foregroundColor, value: UIColor.red, range: firstRange)
                attrTxt.addAttribute(.foregroundColor, value: UIColor.green, range: secondRange)
                attributedText = attrTxt
            }
        }
    }