0

I'm trying to apply formatting on the selected range of the textview. The problem is when the selected text format applied, the rest of text reset its format.

Here is my code:

 if let text = textView.text {  

    if let textRange = textView.selectedTextRange {

          if let selectedText = textView.text(in: textRange) {

                let range = (text as NSString).range(of: selectedText)

                let attributedString = NSMutableAttributedString(string:text)
                attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 18) , range: range)

                self.textView.attributedText = attributedString
            }
        }
    }
NST
  • 115
  • 10
  • Let's clarify: `(NS)String` is just a chains of letters, it doesn't have knowledge of font, colors, etc. It's in theory `UILabel`, `UITextView`, etc, UI stuff to do it. `NSAttributedString` can add theses info to a classic "String" to allow the UIStuff to render differently. So when you do `let attributedString = NSMutableAttributedString(string:text)`, you used `text`, which is a `(NS)String`, and then lost all of its previous content. – Larme Mar 20 '17 at 09:27
  • Instead, in pseudo code, I don't use Swift: `NSMutableAttributedString attributedString = self.textView.attributedText.mutableCopy`, then `attributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 18) , range: range)`, then `self.textView.attributedText = attributedString` – Larme Mar 20 '17 at 09:28
  • @Larme Thank you – NST Mar 20 '17 at 09:35

1 Answers1

2
  let range = textView.selectedRange
  let string = NSMutableAttributedString(attributedString: 
  textView.attributedText)
  let attributes = [NSForegroundColorAttributeName: UIColor.redColor()]
   string.addAttributes(attributes, range: textView.selectedRange)
  textView.attributedText = string
  textView.selectedRange = range
Mahesh Dangar
  • 806
  • 5
  • 11