0

I'm working on a iOS app with Swift. And I have to implement multiple colors for text in UITextField. So far I know how to set color for different parts of UITextField text and how to concatenate them. This is the example of that:

let attributedString = NSMutableAttributedString(string: string, attributes: [:])
attributedString.addAttribute(NSForegroundColorAttributeName,
                                   value: color,
                                   range: NSRange(location: 0, length: string.characters.count))

But when I press delete button and erase some of the text, and when I start wright again, the new text has the color of the last deleted text. I want default color for every new character, regardless which was the last color (color of text when deleting) for text in UITextField. Can I set color or some attribute of text (new text) in this function?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool

So, when new character has been written it will be in my desired color, black for instance. Thanks for your answers.

just_a_dev
  • 183
  • 1
  • 2
  • 9
  • Look at this link..http://stackoverflow.com/questions/14231879/is-it-possible-to-change-color-of-single-word-in-uitextview-and-uitextfield You have to specify length for a color type – Gagan_iOS May 10 '17 at 12:50
  • This doesn't help. – just_a_dev May 10 '17 at 12:58
  • did you try to specify the text length in your code. – Gagan_iOS May 10 '17 at 12:59
  • Yes, I just need to be sure that every new character in UITextField will be In default color. No matter in what color is text in UITextField. – just_a_dev May 10 '17 at 13:02
  • Yes.. thats why I asked for length in the code attributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length: string.characters.count)) here you are considering length of whole string..make length change here as you wish – Gagan_iOS May 10 '17 at 13:05
  • I can't make it work when I change length. – just_a_dev May 10 '17 at 13:46
  • 1
    Look into the `typingAttributes` property of `UITextField`. – rmaddy May 10 '17 at 13:57
  • @rmaddy - Thank you very much! This is just what I needed. `textField.typingAttributes = [NSForegroundColorAttributeName : UIColor.black]` It works now. – just_a_dev May 10 '17 at 14:35

0 Answers0