28

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

4

9 回答 9

50

尝试创建自己的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];
于 2012-08-30T05:17:26.543 回答
28

斯威夫特 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
于 2016-10-08T17:17:42.007 回答
9

这是一个过滤的解决方案。给文本字段一个委托和一个出口并设置 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);
}
于 2013-03-20T19:35:01.553 回答
8

尝试这个 -

NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[textField setFormatter:formatter];
于 2012-08-28T14:42:10.470 回答
4

这是一个斯威夫特版本:

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
}
于 2015-03-16T11:01:08.057 回答
4

在 SWIFT 中,我是这样做的

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

    if ((Int(txtField.stringValue)) < 0){
        // Display error message
    }
    
于 2016-01-22T21:19:10.637 回答
2

[适用于 Swift 3.0.1]

正如其他人所建议的,子类NumberFormatter和覆盖isPartialStringValid方法。最简单的方法是在 xib/storyboard下放置一个NumberFormatter对象并将其更新为. 下一个实现只允许整数或空白值,并在字符串包含非法字符时发出哔哔声。NSTextFieldCustom 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
        }
    }
}

StringnumberOfCharacters()isInt()是在扩展中添加的方法。

extension String {

    func isInt() -> Bool {

        if let intValue = Int(self) {

            if intValue >= 0 {
                return true
            }
        }

        return false
    }

    func numberOfCharacters() -> Int {
        return self.characters.count
    }
}
于 2017-01-18T10:45:54.953 回答
1

这是创建相同的步骤....

只需创建带有子类 NSNumberFormatter 的 ANYCLASS(称为 SAMPLE)...

在 .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;

}

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

NSTextField *mySampleTxtFld;

为此设置格式化程序...

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

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

你完成了!!!

于 2014-03-07T15:09:48.410 回答
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
        }
    }
}
于 2016-03-16T09:12:40.880 回答