user4385051
user4385051

Reputation:

UITextView Color of the selected text

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?

Upvotes: 4

Views: 6232

Answers (1)

Rob
Rob

Reputation: 438287

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

Upvotes: 8

Related Questions