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?
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()
}