Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Clear NSTextField when in focus (OSX)

I would like the textfield to clear when the user selects it so they can begin typing without needing to delete what is already there. To clear the textfield I have the code below but i am not sure how I detect that it is in focus. Thanks

[myTextField setStringValue: @""];

1 Answer

Robert Bojor
PLUS
Robert Bojor
Courses Plus Student 29,439 Points

Hi Tom,

You could use NSTextFieldDelegate and implement a mix of controlTextDidChange:, control:textShouldBeginEditing: and control:textShouldEndEditing: methods like in the code below.

// RBAppDelegate.h
#import <Cocoa/Cocoa.h>
@interface RBAppDelegate : NSObject <NSApplicationDelegate, NSTextFieldDelegate>
@property (assign) IBOutlet NSWindow *window;
@end

// RBAppDelegate.m
#import "RBAppDelegate.h"

@interface RBAppDelegate()
@property (nonatomic) BOOL isEditing;
@end

@implementation RBAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    _isEditing = NO;
}

- (void)controlTextDidChange:(NSNotification *)notification {
    NSTextField *textField = [notification object];
    NSString *stringVal = [textField stringValue];
    if (_isEditing) {
        [textField setStringValue:[stringVal substringFromIndex:[stringVal length]-1]];
        _isEditing = NO;
    }
}

- (BOOL)control:(NSControl *)control textShouldBeginEditing:(NSText *)fieldEditor {
    _isEditing = YES;
    return true;
}
-(BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor {
    _isEditing = NO;
    return true;
}
@end

When you start typing inside the NSText the control:textShouldBeginEditing: is fired first. If you use this method to clear out your text field you will lose your first letter that was pressed, which is not very nice...

However, the controlTextDidChange: is fired every time you press a key inside the NSText field but the value of the text field is already updated to include the pressed key. Using the _isEditing bool we can test is the editing has begun, set the text field value to the last key that was pressed - using the substringFromIndex: method - and reset the _isEditing back to false so on the next key press nothing affects the text field value.

Hope this helped. Cheers!

Thank you