Friday, April 10, 2015

Cocoa OSX NSTextField Select All Text On Focus

Hello,

Recently I was working on MAC application where there was a requirement to select text inside NSTextField as soon as user focus it. In this blog I am going to explain how to do this.

First add a class to your project and name is CustomTextField. It will create two files CustomTextField.h and CustomTextField.m

Open CustomTextField.h file and add following code to it.

#import

@interface CustomTextField : NSTextField


@end

Now open CustomTextField.m file and add following code to it.

#import "CustomTextField.h"

@implementation CustomTextField

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    
    // Drawing code here.
}

- (BOOL)becomeFirstResponder
{
    BOOL result = [super becomeFirstResponder];
    if(result){
        [self performSelector:@selector(selectText:) withObject:self afterDelay:0];
    }
    return result;
}
@end

As you can see we have added event handler for becomeFirstResponder event. This event is fired as soon as user focus the text field. In that function we are selecting text by calling selector selectText with zero second delay. This will immediately select the text as soon as user focus on it. Now go to your Storyboard or xib file and select the TextField in which you want this behavior. 

Go to identity inspector and select the class CustomTextField for your textfield.

That's it.You can also do additional stuff like changing background color on focus.

[self setBackgroundColor:[NSColor clearColor]];
[self setBackgroundColor:[NSColor redColor]];

Hope this helps you. 

No comments:

Post a Comment