问题
I've been trying to figure out how to auto erase a string within an NSTextField upon clicking within in it.
For example the current behavior is like this on OSX:
When a user clicks in the cell or the default focus is the cell either the word is sometimes highlighted or the cursor is placed in the middle of the text. The user then needs to use backspace to delete the text (which I'd like to eliminate by automatically removing the text).
Is this a function that is built-in that I'm somehow missing? If not how would I go about it?
回答1:
As far as I know there is no standard function to delete the text that is in the textfield. Depending on your controller class you can try to work with mouseDown or acceptFirstResponder, but I don't believe this will provide a stable situation.
I would recommend you to start with an empty textfield (setting in xcode) and empty the textfield after the content of the textfield has been processed. For instance:
-(IBAction)addYourTextFieldInWhateverYouWant:(id)sender
{
//copying the string from the textfield
NSString *text = [[self yourTextField]stringValue];
//now you can empty the textfield
[[self yourTextField]setStringValue:@""]
//Do here whatever you need to do with the input from the textfield.
....
}
It doesn't give you exactly what you want, but it provides the user with an empty textfield where the user can immediately type in his/her text when the textfield is clicked upon and the user doesn't need to delete any text in the textfield.
Hope this helps.
Kind regards, MacUserT
回答2:
There are plenty of terrible ideas “outside the box”, and this is one of them.
Anyway, make a subclass of NSTextField. Override becomeFirstResponder. If [super becomeFirstResponder] returns YES, set self.stringValue = @"".
来源:https://stackoverflow.com/questions/28530167/objective-c-auto-erase-nstextfield-string