SashDing SashDing - 5 months ago 26
Swift Question

Change typing color in Swift TextView

How to change the color by pressing typing in TextView?

For example, I type in black, and then press the button of color orange and more print text in orange color, then I press on the black button and print black text?

The studied methods can have the color of all typed text or placeholders etc.


Try this way:

@IBAction func blackButtonClicked(sender: UIButton) {
    let attributedText = textView.attributedText

    textView.textColor = UIColor.blackColor()
    textView.attributedText = attributedText

@IBAction func redButtonClicked(sender: UIButton) {
    let attributedText = textView.attributedText

    textView.textColor = UIColor.redColor()
    textView.attributedText = attributedText

enter image description here

You can also achieve this by setting the typingAttributes property of the textView, which seems to be a nicer solution:

@IBAction func redButtonClicked() {
  textView.typingAttributes[NSForegroundColorAttributeName] = UIColor.redColor()

@IBAction func blackButtonClicked() {
  textView.typingAttributes[NSForegroundColorAttributeName] = UIColor.blackColor()