0

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

2 Answers2

1

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
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

Try to use function like below

text_lbl.attributedText = self.decorateText(txt1: "Red Color", txt2: “Blue Color”)


func decorateText(txt1:String, txt2:String)->NSAttributedString{
    let textAttributesOne = [NSAttributedStringKey.foregroundColor: UIColor.red, NSAttributedStringKey.font: UIFont(name: "Poppins-Regular", size: 12.0)!] as [NSAttributedStringKey : Any]
    let textAttributesTwo = [NSAttributedStringKey.foregroundColor: UIColor.blue, NSAttributedStringKey.font: UIFont(name: "Poppins-SemiBold", size: 14.0)!] as [NSAttributedStringKey : Any]

    let textPartOne = NSMutableAttributedString(string: txt1, attributes: textAttributesOne)
    let textPartTwo = NSMutableAttributedString(string: txt2, attributes: textAttributesTwo)

    let textCombination = NSMutableAttributedString()
    textCombination.append(textPartOne)
    textCombination.append(textPartTwo)
    return textCombination
}
Yogesh Tandel
  • 1,738
  • 1
  • 19
  • 25