how to get a text field to clear when entering

I swear I coudn’t find a solution in searching the board, although this seems simple?

How can I get a text field to clear any existing text when it is clicked on (for entering a new value or text)

Thanks for any help…
Mark

hmm - I don’t know if there is a pure Applescript way to do this - but you could simply subclass NSTextField to add such a behaviour:

MyTextField.h

#import <Cocoa/Cocoa.h>

@interface MyTextField : NSTextField {}
@end

MyTextField.m

#import "MyTextField.h"

@implementation MyTextField
- (void)mouseDown:(NSEvent *)theEvent {
	[super mouseDown];
	[self setStringValue:@""];
}
@end

D.

btw. if you want to have the TextField cleared not only when mouseclicked (but also when entered with tab via the keyboard) then use this instead of -(void)mousedown:(NSEvent *)theEvent …


- (BOOL)becomeFirstResponder {
	BOOL retVal = [super becomeFirstResponder];
	[self setStringValue:@""];
	return retVal;
}

one last idea - maybe this is the user-friendliest version?

you could add the behaviour of tab (selecting all text so it can easily be overwritten) to mouseDown:


- (void)mouseDown:(NSEvent *)theEvent { // selects all text of the NSTextField every time it is clicked
	[super mouseDown];
	[self selectText:self];
}

thanks for the help, I’ll try this when I get the hang of calling c routines…

Hi POSTMARK,

it’s not necessary to call this from your AS - just follow these steps:

  1. open you user interface in interface builder

  2. select the tab ‘Classes’ in the main window

  3. select one of the text fields you want to edit in your GUI - you’ll notice that ‘NSTextfield’ is selected now in the main window

  4. Control-click NSTextfield and choose ‘Subclass NSTextfield’ - give it a name, for example ‘MyTextfield’

  5. Control-click the new entry ‘MyTextfield’ and choose ‘Create files for MyTextfield’

  6. Enter Command+5 → the inspector shows now ‘custom class’ - you have two options: ‘NSTextField’ and ‘MyTextfield’ - switch to ‘MyTextfield’. Repeat step 6 for all Textfields you want the new behaviour for.

  7. save all changes in interface builder

  8. edit the two files ‘MyTextfield.h’ and ‘MyTextfield.m’ in xCode as described above.

Save and Build. You are done. The text fields should now behave as expected.

Goold luck :slight_smile:

D.