Home > database >  How get textview attributed text?
How get textview attributed text?

Time:10-25

I have UITextView text_recepty in which I write text with different colors. In my solution, I need to add colored text, but the original text and colors must remain the same. Is there a way to get the original text with colors correctly?

var toastcolor: UIColor = UIColor.black
var toast: String = "TEST..."            
         
            if ChodButtonisOn == true {
                
                toastcolor = UIColor(red: 118/255, green: 110/255, blue: 38/255, alpha: 1.0)
                
            } else {
                
                if HalfButtonisOn == true {
                toastcolor = UIColor(red: 240/255, green: 127/255, blue: 18/255, alpha: 1.0)
                }
            }
            
            let text1 = NSMutableAttributedString(string: text_recepty.text!)
            let attr2 = [NSAttributedString.Key.foregroundColor: toastcolor]
            let text2 = NSAttributedString(string: toast   "\n", attributes: attr2)
            text1.append(text2)
                
            text_recepty.attributedText = text1
            ```

CodePudding user response:

You need to get the attributedText from the UITextView and then append new text to it like:

let existingText = myTextView.attributedText
let mutableText = NSAttributedString(attributedString: existingText)

// Then add your text

Check NSMutableAttributedString docs for how to do the last part.

  • Related