UITextView Color of selected text

If I have UITextViewc textview.selectable = trueand I want to change the selected TextColor using UIButton, how to do it using Swift?

+4
source share
1 answer

If you want to change the selected row range, you must change the property attributedText. You can do something like:

@IBAction func didTapButton(sender: UIButton) {
    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
}

If you want to change the entire line, you can use the technique suggested by CeceXX.

@IBAction func didTapButton(sender: UIButton) {
    textView.textColor = UIColor.redColor()
}
+6
source

All Articles