Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change border "glow" color of NSTextField

I have an NSText field in MainMenu.xib and I have an action set to validate it for an email address. I want the NSTexFields border color (That blue glow) to be red when my action returns NO and green when the action returns YES. Here is the action:

-(BOOL) validEmail:(NSString*) emailString {
    NSString *regExPattern = @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$";
    NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern     options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
    NSLog(@"%ld", regExMatches);
    if (regExMatches == 0) {
        return NO;
    } else
        return YES;
}  

I call this function and setting the text-color right now, but I would like to set the NSTextField's glow color instead.

- (void) controlTextDidChange:(NSNotification *)obj{
    if ([obj object] == emailS) {
        if ([self validEmail:[[obj object] stringValue]]) {
            [[obj object] setTextColor:[NSColor colorWithSRGBRed:0 green:.59 blue:0 alpha:1.0]];
            [reviewButton setEnabled:YES];
        } else {
            [[obj object] setTextColor:[NSColor colorWithSRGBRed:.59 green:0 blue:0 alpha:1.0]];
            [reviewButton setEnabled:NO];
        }
    }
}

I am open to sub-classing NSTextField, but the cleanest way to do this would be greatly appreciated!

like image 416
benj9a4 Avatar asked Apr 18 '13 01:04

benj9a4


1 Answers

My solution for Swift 2 is


    @IBOutlet weak var textField: NSTextField!

...

// === set border to red ===
// if text field focused right now
NSApplication.sharedApplication().mainWindow?.makeFirstResponder(self)
// disable following focusing
textField.focusRingType = .None
// enable layer
textField.wantsLayer = true
// change border color
textField.layer?.borderColor = NSColor.redColor().CGColor
// set border width
textField.layer?.borderWidth = 1

like image 111
avvensis Avatar answered Oct 10 '22 11:10

avvensis