在 `controlTextDidChange` 方法中使用自定义 NSFormatter 访问 NSTextField 的 `stringValue` 使其不可编辑。

Accessing `stringValue` of a NSTextField with custom NSFormatter, in `controlTextDidChange` method makes it non-editable.

我有一个自定义 NSFormatter 文本字段,如 here & here 中所述。我也有此文本字段的委托,我正在从委托方法 controlTextDidChange: 访问 stringValue。使用此代码,当我尝试编辑文本字段时,它会不断从 NSFormatter 重置它的值并使其不可编辑。

CustomFormatter.m

 @implementation CustomFormatter

- (BOOL)getObjectValue:(id *)obj forString:(NSString *)string errorDescription:(NSString  **)error {
    float floatResult;
    NSScanner *scanner;
    BOOL returnValue = NO;

    scanner = [NSScanner scannerWithString: string];
    [scanner scanString: @"$" intoString: NULL]; // ignore  return value
    if ([scanner scanFloat:&floatResult] && ([scanner isAtEnd])) {
        returnValue = YES;
        if (obj) {
            *obj = [NSNumber numberWithFloat:floatResult];
        }
    } else {
        if (error) {
            *error = NSLocalizedString(@"Couldn’t convert  to float", @"Error converting");
        }
    }
    return returnValue;
}

- (NSString *)stringForObjectValue:(id)anObject {

    if (![anObject isKindOfClass:[NSNumber class]]) {
        return nil;
    }
    return [NSString stringWithFormat:@"$%.2f", [anObject  floatValue]];
}

@end

MyDelegate.m

@interface MyController () <NSTextFieldDelegate>
@property (weak) IBOutlet NSTextField *text1;    
@end

@implementation MyController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
}

- (void)controlTextDidChange:(NSNotification *)obj {
    NSLog(@"%@",[self.text1 stringValue]);
}
@end

你可以从field editor中得到字符串,一个NSTextView。您可以从通知的用户信息中获取字段编辑器。

controlTextDidChange

This method is invoked when text in a control such as a text field or form changes. The control posts a textDidChangeNotification notification, and if the control’s delegate implements this method, it is automatically registered to receive the notification. Use the key @"NSFieldEditor" to obtain the field editor from the userInfo dictionary of the notification object.