Search code examples
objective-cmacoscocoanstextfieldnssearchfield

NSTextField / NSSearchField default value that is removed when focus is on the field


I would like to have a default value for a NSTextField (or NSSearchField) and have this default value removed when the user clicks on it and set back when the text view loses the focus and the text field is empty. Like this:

http://imgur.com/T03vE

It sounds like I should extend NSSearchField but I was wondering if there was an easier solution.


Solution

  • This functionality is in fact built-in; there's no need to subclass or otherwise extend NSSearchField.

    That's the field's placeholder string. You can set it either in IB or via a call to setPlaceholderString:. Notice that this is a method of NSTextFieldCell. An NSTextField is the "public face" of its cell, and has cover methods for almost all of the cell's functionality. In this case, however, you need to send the message directly to the cell:

    [[field cell] setPlaceholderString:@"Jumbo jets"];
    

    Since NSSearchField and NSSearchFieldCell inherit from NSTextField and NSTextFieldCell, respectively, the process is the same for them.