Search code examples
iphoneiosuitextfield

Two different colors inside an UITextField


I have an UITextField where the initial text is "username.mysite.com". The default color (Black) is set.

I would like to have "username" with a different color like gray. Is it possible?

User can click the "Clear Button", than the placeholder is "url".


Solution

  • Can't be done with a UITextField directly. Your basic two options are:

    1. Use a UIWebView masquerading as a text field. This is easy, but is a sledge hammer and can incur performance penalties in certain use cases.

    2. Use Core Text to display a duly configured NSAttributedString. Though the link appears to be for Mac OS, Core Text exists on iOS too. The framework is very powerful but has a steep learning curve and doesn't support editable text out of the box. There are, however, various open source libraries that might of help getting started (e.g. DTCoreText. OHAttributedLabel).