4

If I have UITextView with textview.selectable = true, and I want to change a selected TextColor using a UIButton, How can I do this Using swift?

Charuක
  • 12,953
  • 5
  • 50
  • 88

1 Answers1

8

If you just want to change the selected range of the string, you must change the attributedText property. 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 whole string, you can use the technique suggested by CeceXX.

@IBAction func didTapButton(sender: UIButton) {
    textView.textColor = UIColor.redColor()
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044