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?
Asked
Active
Viewed 6,180 times
4

Charuක
- 12,953
- 5
- 50
- 88
-
Did you find a fix? If yes, please post the correct answer. – Cesare Jan 25 '15 at 11:33
1 Answers
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