Search code examples
swifttextviewnsmutableattributedstring

Swift 3 - Change the font of UITextView's selected text


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
            }
        }
    }

Solution

  •   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