8

我在 MainMenu.xib 中有一个 NSText 字段,并且我设置了一个操作来验证它的电子邮件地址。我希望 NSExFields 边框颜色(蓝色发光)在我的操作返回 NO 时为红色,而在操作返回 YES 时为绿色。这是动作:

-(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;
}  

我现在调用这个函数并设置文本颜色,但我想设置 NSTextField 的发光颜色。

- (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];
        }
    }
}

我对子类 NSTextField 持开放态度,但最干净的方法将不胜感激!

4

2 回答 2

5

我对 Swift 2 的解决方案是


    @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

于 2016-08-13T10:02:17.350 回答
0

The way to go about this is to subclass NSTextFieldCell and draw your own focus ring. As far as I can tell there's no way to tell the system to draw the focus ring using your own color, so you'll have to call setFocusRingType:NSFocusRingTypeNone, check if the control has first responder status in your drawing method, and if so draw a focus ring using your own color.

If you decide to use this approach remember that the focus ring is a user defined style (blue or graphite), and there's no guarantee future versions of OSX won't allow the user to change the standard color to red or green. It's also likely the focus ring drawing style will change in future versions of OSX, at which point you'll have to update your drawing code in order for things to look right.

于 2014-03-26T23:32:47.227 回答