将NSTextField限制为仅允许数字 [英] Restrict NSTextField to only allow numbers

查看:890
本文介绍了将NSTextField限制为仅允许数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何限制 NSTextfield 只允许数字/整数?我发现这样的问题,但他们没有帮助!

How do I restrict a NSTextfield to allow only numbers/integers? I've found questions like this one, but they didn't help!

推荐答案

尝试创建自己的 NSNumberFormatter 子类并检查输入值 -isPartialStringValid:newEditingString:errorDescription:方法。

Try to make your own NSNumberFormatter subclass and check the input value in -isPartialStringValid:newEditingString:errorDescription: method.

@interface OnlyIntegerValueFormatter : NSNumberFormatter

@end

@implementation OnlyIntegerValueFormatter

- (BOOL)isPartialStringValid:(NSString*)partialString newEditingString:(NSString**)newString errorDescription:(NSString**)error
{
    if([partialString length] == 0) {
        return YES;
    }

    NSScanner* scanner = [NSScanner scannerWithString:partialString];

    if(!([scanner scanInt:0] && [scanner isAtEnd])) {
        NSBeep();
        return NO;
    }

    return YES;
}

@end

然后将此格式化程序设置为 NSTextField

And then set this formatter to your NSTextField:

OnlyIntegerValueFormatter *formatter = [[[OnlyIntegerValueFormatter alloc] init] autorelease];
[textField setFormatter:formatter];

这篇关于将NSTextField限制为仅允许数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆