ios UITextField 应该只接受数字值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10734959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:29:56  来源:igfitidea点击:

UITextField Should accept number only values

iosobjective-ciphonexcodeuitextfield

提问by james

I have UITexfields i want that it should accept only number other shows alert that enter a numeric value. I want that motionSicknessTextFiled should only accept number

我有 UIExfields 我希望它应该只接受输入数字值的其他显示警报的数字。我希望motionSicknessTextFiled 应该只接受数字

NSString*dogswithMotionSickness=motionSicknessTextField.text;
NSString*valueOne=cereniaTextField.text;
NSString*valueTwo=prescriptionTextField.text;
NSString*valueThree=otherMeansTextField.text;
NSString*valueFour=overtheCounterTextField.text;

回答by Michael Dautermann

In whatever UITextField you're getting these values from, you can specify the kind of keyboard you want to appear when somebody touches inside the text field.

无论您从哪个 UITextField 获取这些值,您都可以指定当有人触摸文本字段时要显示的键盘类型。

E.G. a numeric-only keyboard.

EG 仅数字键盘。

Like this screenshot:

像这个截图:

numeric only keyboard will appear

将出现仅数字键盘

This is easily set when working with the XIB and the Interface Builder built into Xcode, but if you want to understand this programmatically, take a look at Apple's UITextInputTraitsprotocol reference page, specifically the keyboardTypepropertyinformation.

这在使用 XIB 和内置于 Xcode 的 Interface Builder 时很容易设置,但如果您想以编程方式理解这一点,请查看 Apple 的UITextInputTraits协议参考页面,特别是keyboardType属性信息。

To filter out punctuations, set the textfield's delegate and set up the shouldChangeCharactersInRange method:

要过滤掉标点符号,请设置文本字段的委托并设置 shouldChangeCharactersInRange 方法:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
? ? NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:textField.text];

? ? BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
? ? return stringIsValid;
}

回答by Himanshu padia

Objective C

目标 C

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (!string.length) 
        return YES;

    if (textField == self.tmpTextField)
    {
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSString *expression = @"^([0-9]+)?(\.([0-9]{1,2})?)?$";
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression 
                                                                               options:NSRegularExpressionCaseInsensitive 
                                                                                 error:nil];
        NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
                                                            options:0
                                                              range:NSMakeRange(0, [newString length])];        
        if (numberOfMatches == 0)
            return NO;        
    }
    return YES;
}

Swift 3.0

斯威夫特 3.0

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if !string.characters.count {
        return true
    }
    do {
        if textField == self.tmpTextField {
            var newString = textField.text.replacingCharacters(inRange: range, with: string)
            var expression = "^([0-9]+)?(\.([0-9]{1,2})?)?$"
            var regex = try NSRegularExpression(pattern: expression, options: NSRegularExpressionCaseInsensitive)
            var numberOfMatches = regex.numberOfMatches(inString: newString, options: [], range: NSRange(location: 0, length: newString.characters.count))
            if numberOfMatches == 0 {
                return false
            }
        }
    }
    catch let error {
    }
    return true
}

回答by Martol1ni

[textField setKeyboardType:UIKeyboardTypeNumberPad];

回答by Almas Adilbek

I've implemented the snippet which has the features for textField:

我已经实现了具有 textField 功能的代码段:

  1. Check the maximum allowedcharacters.
  2. Check the valid decimalnumber.
  3. Check only numericnumbers.
  1. 检查允许最大字符数。
  2. 检查有效的十进制数。
  3. 只检查数字

The code is the UITextFielddelegate method. Before you use this snippet, you must have these properties:

代码是UITextField委托方法。在使用此代码段之前,您必须具有以下属性:

  1. self.maxCharacters
  2. self.numeric// Only intcharacters.
  3. self.decimalNumeric// Only numbers and ".", "," (for specific locales, like Russian).
  1. self.maxCharacters
  2. self.numeric// 只有int字符。
  3. self.decimalNumeric// 只有数字和“.”、“、”(针对特定语言环境,如俄语)。

Code:

代码:

- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(self.numeric || self.decimalNumeric)
    {
        NSString *fulltext = [textField.text stringByAppendingString:string];
        NSString *charactersSetString = @"0123456789";

        // For decimal keyboard, allow "dot" and "comma" characters.
        if(self.decimalNumeric) {
            charactersSetString = [charactersSetString stringByAppendingString:@".,"];
        }

        NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:charactersSetString];
        NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:fulltext];

        // If typed character is out of Set, ignore it.
        BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
        if(!stringIsValid) {
            return NO;
        }

        if(self.decimalNumeric)
        {
            NSString *currentText = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

            // Change the "," (appears in other locale keyboards, such as russian) key ot "."
            currentText = [currentText stringByReplacingOccurrencesOfString:@"," withString:@"."];

            // Check the statements of decimal value.
            if([fulltext isEqualToString:@"."]) {
                textField.text = @"0.";
                return NO;
            }

            if([fulltext rangeOfString:@".."].location != NSNotFound) {
                textField.text = [fulltext stringByReplacingOccurrencesOfString:@".." withString:@"."];
                return NO;
            }

            // If second dot is typed, ignore it.
            NSArray *dots = [fulltext componentsSeparatedByString:@"."];
            if(dots.count > 2) {
                textField.text = currentText;
                return NO;
            }

            // If first character is zero and second character is > 0, replace first with second. 05 => 5;
            if(fulltext.length == 2) {
                if([[fulltext substringToIndex:1] isEqualToString:@"0"] && ![fulltext isEqualToString:@"0."]) {
                    textField.text = [fulltext substringWithRange:NSMakeRange(1, 1)];
                    return NO;
                }
            }
        }
    }

    // Check the max characters typed.
    NSUInteger oldLength = [textField.text length];
    NSUInteger replacementLength = [string length];
    NSUInteger rangeLength = range.length;

    NSUInteger newLength = oldLength - rangeLength + replacementLength;
    BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;

    return newLength <= _maxCharacters || returnKey;
}

Demo:

演示:

enter image description here

在此处输入图片说明

回答by Hsm

Modified Michael Dautermann's answer:

修改 Michael Dautermann 的回答:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(string.length > 0)
    {
        NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];

        BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
        return stringIsValid;
    }
    return YES;
}

回答by pchelnikov

Here is Swift solution:

这是Swift解决方案:

In viewDidLoad set the delegate:

在 viewDidLoad 中设置委托:

_yourTextField.delegate = self
let _acceptableCharacters = "0123456789."

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if (string.characters.count == 0) {
        return true
    }

    if (textField == self._yourTextField) {
        let cs = NSCharacterSet(charactersInString: self._acceptableCharacters)
        let filtered = string.componentsSeparatedByCharactersInSet(cs).filter {  !
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
  let compSepByCharInSet = string.components(separatedBy: aSet)
  let numberFiltered = compSepByCharInSet.joined(separator: "")

  if string == numberFiltered {
    let currentText = textField.text ?? ""
    guard let stringRange = Range(range, in: currentText) else { return false }
    let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
    return updatedText.count <= 10
  } else {
    return false
  }
}
.isEmpty } let str = filtered.joinWithSeparator("") return (string != str) } return true }

回答by ravi alagiya

swift 4

迅捷 4

This allows only number input and you can also set character limitation

这仅允许输入数字,您还可以设置字符限制

+(BOOL) checkforNumeric:(NSString*) str
{
    NSString *strMatchstring=@"\b([0-9%_.+\-]+)\b"; 
    NSPredicate *textpredicate=[NSPredicate predicateWithFormat:@"SELF MATCHES %@", strMatchstring];

    if(![textpredicate evaluateWithObject:str])
    {
        //////NSLog(@"Invalid email address found");
        UIAlertView *objAlert = [[UIAlertView alloc] initWithTitle:APP_NAME message:@"please enter valid text." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Close",nil];
        [objAlert show];
        [objAlert release];
        return FALSE;
    }
    return TRUE;
}

回答by Prabhat Kasera

this is the function which checks for the String contains Numeric value only

这是检查字符串仅包含数字值的函数

yourTxtField.delegate = self;

check it on submit button.

在提交按钮上检查它。

回答by MasterRazer

I just modified the answer of Michael and made it a little bit easier to implement. Just make sure that the delegate of your UITextfieldis set to itself.

我只是修改了迈克尔的答案,让它更容易实现。只需确保您的委托UITextfield设置为它自己。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  {

    if (textField == yourTxtField) {
        NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];

        BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
            return stringIsValid;
        }else {
            return YES;
        }
    }

Furthermore copy & paste this code into your main file.

此外,将此代码复制并粘贴到您的主文件中。

@"0123456789" -> @"0123456789 "

If you want to allow the use of the spacebar just put in a blank space at the end of the CharactersInString, just like so:

如果您想允许使用空格键,只需在 末尾添加一个空格CharactersInString,就像这样:

if (textField == yourTxtField) {
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return (([string isEqualToString:filtered])&&(newLength <= 10));

    }

Additionally:

此外:

If you want to restrict the length of the string just replace the if-function with following:

如果要限制字符串的长度,只需将 if 函数替换为以下内容:

private let kMaxTextLength = 8
private let kZeroDotted = "0."
private let kZero = "0"
private let kDoubleDot = ".."
private let kDot = "."
private let kPeriod = ","

In my case the "10" at the end represents the limit of characters.

就我而言,末尾的“10”代表字符数限制。

Cheers! :)

干杯! :)

回答by Michael

Swift 4.2 port of the best answer here by @almas-adlibek

@almas-adlibek 最佳答案的 Swift 4.2 端口

A bunch of configuration variables:

一堆配置变量:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    guard let oldText = textField.text, let swiftRange = Range(range, in: oldText) else {
        return true
    }

    let newText = oldText.replacingCharacters(in: swiftRange, with: string)

    var currentText =  textField.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)

    // Change the "," (appears in other locale keyboards, such as russian) key ot "."
    currentText = currentText?.replacingOccurrences(of: kPeriod, with: kDot)

    // Check the statements of decimal value.
    if (newText == kDot) {
        textField.text = kZeroDotted;
        return false
    }

    if (newText.range(of: kDoubleDot) != nil) {
        textField.text = newText.replacingOccurrences(of: kDoubleDot, with: kDot);
        return false
    }

    // If second dot is typed, ignore it.
    let dots = newText.components(separatedBy: kDot)
    if(dots.count > 2) {
        textField.text = currentText;
        return false
    }

    // If first character is zero and second character is > 0, replace first with second. 05 => 5;
    if(newText.count == 2) {
        if(newText[0...0] == kZero && newText != kZeroDotted) {
            textField.text = newText[1...1]
            return false
        }
    }

    // Check the max characters typed.
    let oldLength = textField.text?.count ?? 0
    let replacementLength = string.count
    let rangeLength = range.length

    let newLength = oldLength - rangeLength + replacementLength;
    let returnKey = string.rangeOfCharacter(from: CharacterSet.newlines) != nil

    return newLength <= kMaxTextLength || returnKey;
}

Now the Swift 4 converted part of the code.

现在 Swift 4 转换了部分代码。

##代码##