将NSTextField限制为仅允许数字

时间:2012-08-28 14:35:11

标签: cocoa nstextfield

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

9 个答案:

答案 0 :(得分:44)

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

@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

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

答案 1 :(得分:15)

Swift 3版

import Foundation

    class OnlyIntegerValueFormatter: NumberFormatter {

    override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {

        // Ability to reset your field (otherwise you can't delete the content)
        // You can check if the field is empty later
        if partialString.isEmpty {
            return true
        }

        // Optional: limit input length
        /*
        if partialString.characters.count>3 {
            return false
        }
        */

        // Actual check
        return Int(partialString) != nil
    }
}

使用:

let onlyIntFormatter = OnlyIntegerValueFormatter()
myNsTextField.formatter = onlyIntFormatter

答案 2 :(得分:8)

试试这个 -

NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[textField setFormatter:formatter];

答案 3 :(得分:8)

这是一个带过滤的解决方案。给textfield的委托和出口并设置controlTextDidChange方法。

- (void)controlTextDidChange:(NSNotification *)aNotification {

    NSTextField *textfield = [notification object];
    NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];

    char *stringResult = malloc([textfield.stringValue length]);
    int cpt=0;
    for (int i = 0; i < [textfield.stringValue length]; i++) {
        unichar c = [textfield.stringValue characterAtIndex:i];
        if ([charSet characterIsMember:c]) {
            stringResult[cpt]=c;
            cpt++;
        }
    }
    stringResult[cpt]='\0';
    textfield.stringValue = [NSString stringWithUTF8String:stringResult];
    free(stringResult);
}

答案 4 :(得分:4)

这是一个Swift版本:

override func isPartialStringValid(partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool {
    if (count(partialString.utf16)) {
        return true
    }

    if (partialString.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) != nil) {
        NSBeep()
        return false
    }

    return true
}

答案 5 :(得分:3)

在SWIFT中,我是这样做的

  1. 使用Int()
  2. 将文本值转换为Int
  3. 检查转换后的值是否不小于0
  4. 如果小于0,则显示错误消息,其他接受值

    if ((Int(txtField.stringValue)) < 0){
        // Display error message
    }
    

答案 6 :(得分:2)

[适用于Swift 3.0.1]

正如其他人所建议的那样,子类NumberFormatter并覆盖isPartialStringValid方法。最简单的方法是将NumberFormatter对象放在xib / storyboard中的NSTextField下,然后更新Custom Class。 下一个实现只允许整数或空值,如果字符串包含非法字符,则会发出蜂鸣声。

class IntegerFormatter: NumberFormatter {

    override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {

        // Allow blank value
        if partialString.numberOfCharacters() == 0  {
            return true
        }

        // Validate string if it's an int
        if partialString.isInt() {
            return true
        } else {
            NSBeep()
            return false
        }
    }
}

String的{​​{1}}和numberOfCharacters()是扩展程序中添加的方法。

isInt()

答案 7 :(得分:1)

以下是创建相同内容的步骤....

创建ANYCLASS(称为SAMPLE),并对NSNumberFormatter进行子类化...

<。>在.m文件中编写以下代码...

 - (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString      **)newString errorDescription:(NSString **)error {
// Make sure we clear newString and error to ensure old values aren't being used
if (newString) { *newString = nil;}
if (error) {*error = nil;}

static NSCharacterSet *nonDecimalCharacters = nil;
if (nonDecimalCharacters == nil) {
    nonDecimalCharacters = [[NSCharacterSet decimalDigitCharacterSet] invertedSet] ;
}

if ([partialString length] == 0) {
    return YES; // The empty string is okay (the user might just be deleting everything and starting over)
} else if ([partialString rangeOfCharacterFromSet:nonDecimalCharacters].location != NSNotFound) {
    return NO; // Non-decimal characters aren't cool!
}

return YES;

}

现在..在您的Actual Class中将格式化程序设置为您的NSTextField对象,如下所示......

NSTextField *mySampleTxtFld;

为此设置Formatter ...

SAMPLE* formatter=[[SAMPLE alloc]init];// create SAMPLE FORMATTER OBJECT 

self.mySampleTxtFld.delegate=self;
[self.mySampleTxtFld setFormatter:formatter];

你做完了!!!

答案 8 :(得分:1)

Swift 2.0自定义格式化程序,带0而不是空格:

class OnlyIntegerValueFormatter: NSNumberFormatter {

    override func isPartialStringValid(partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool {

        if partialString.isEmpty {
            newString.memory = "0"
            return false
        }

        if Int(partialString) < 0 {
            NSBeep()
            return false
        } else {
            return true
        }
    }
}