3

I'm trying to set the font and text color for an attributed string like this:

var attributedString = NSMutableAttributedString(string: myText, attributes: [.font : myFont, .foregroundColor: myTextColor])

Later on, I'm adding more text to this attributed string.

If the myText variable contains some text this works great - the text is displayed with the correct font and text color. However, if myText is an empty string, the attributes aren't added, which means that when I later add more text to the attributed string, it's displayed in black with the default Helvetica 12px font.

Is it possible to add attributes to an attributed string even if the actual text is an empty string?

I'm using this in a UITextView and if the user removes all text in the textview, causing the attributed string to be an empty string, all text formatting is removed as well, which means that any further text additions will be displayed using the default Helvetica font, instead of the font I wish to use.

rodskagg
  • 3,827
  • 4
  • 27
  • 46
  • Are these attributes consistent throughout the textview i.e are you using different fonts or color for different ranges in the textview? – Md. Ibrahim Hassan Jun 25 '18 at 13:33
  • If it's the same attributes for the whole text, (`UITextView` or `UITextField`), and you are only interested in font & foreground, then don't use `NSAttributedString`, use `String` and the the `font` property and `textColor` property of the `UITextView`/`UITextField`. Else you can check the `typingAttributes` properties of them. – Larme Jun 25 '18 at 13:41
  • The user can format the text in different ways - making text bold etc - but the font is always the same, but with different traits (bold, italic etc) – rodskagg Jun 25 '18 at 13:45

0 Answers0