UITextField应该只接受数字值

时间:2012-05-24 09:43:40

标签: ios objective-c iphone xcode uitextfield

我有UITexfields我希望它只接受输入数值的其他数字警告。 我希望motionSicknessTextFiled只接受数字

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

14 个答案:

答案 0 :(得分:53)

在你从中获取这些值的UITextField中,你可以指定当某人触摸文本字段时你想要出现的键盘类型。

E.G。一个纯数字键盘。

喜欢此屏幕截图:

numeric only keyboard will appear

使用XIB和Xcode内置的Interface Builder时可以很容易地设置它,但是如果你想以编程方式理解它,请查看Apple的UITextInputTraits protocol reference page, specifically the keyboardType property信息。

要过滤掉标点符号,请设置文本字段的委托并设置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;
}

答案 1 :(得分:25)

目标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

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
}

答案 2 :(得分:10)

[textField setKeyboardType:UIKeyboardTypeNumberPad];

答案 3 :(得分:7)

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

  1. 检查允许的最大字符。
  2. 检查有效小数号码。
  3. 仅选中数字数字。
  4. 代码是UITextField委托方法。在使用此代码段之前,您必须具有以下属性:

    1. self.maxCharacters
    2. self.numeric //仅 int 个字符。
    3. self.decimalNumeric //只有数字和"。","," (对于特定的语言环境,如俄语)。
    4. 代码:

      - (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;
      }
      

      演示:

      enter image description here

答案 4 :(得分:5)

修改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;
}

答案 5 :(得分:2)

这是Swift解决方案:

在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 {  !$0.isEmpty }
        let str = filtered.joinWithSeparator("")

        return (string != str)
    }

    return true
}

答案 6 :(得分:1)

这是检查String仅包含数值的函数

+(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;
}

在提交按钮上查看。

答案 7 :(得分:1)

这对我有用

迅速4

以上功能仅用于文本字段输入数字,还可以设置字符限制。

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
            }
}

答案 8 :(得分:0)

我刚刚修改了迈克尔的答案并使其更容易实现。只需确保UITextfield的代理设置为自己。

yourTxtField.delegate = self;

此外,复制&amp;将此代码粘贴到主文件中。

- (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;
        }
    }

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

@"0123456789" -> @"0123456789 "

此外:

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

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));

    }

在我的情况下,末尾的“10”表示字符的限制。

干杯! :)

答案 9 :(得分:0)

This answer在Swift 3中引发了一些错误,这是正确的答案:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.characters.count == 0 {
        return true
    }
    do {
        if textField == self.numberTextField {

            let nString = textField.text as NSString?
            let newString = nString?.replacingCharacters(in: range, with: string)
            let expression = "^([0-9]+)?(\\.([0-9]{1,2})?)?$"
            let regex = try NSRegularExpression(pattern: expression, options: .caseInsensitive)
            let numberOfMatches = regex.numberOfMatches(in: newString! as String, options: [], range: NSRange(location: 0, length: (newString?.characters.count)!))

            if numberOfMatches == 0 {
                return false
            }
        }
    }
    catch let error {
    }
    return true
}

答案 10 :(得分:0)

@ almas-adlibek在这里迅速回答4.2最佳答案

一堆配置变量:

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

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

 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;
}

答案 11 :(得分:-1)

<强>夫特

class ExampleVC: UIViewController {

    let numbers = "0123456789";

    override func viewDidLoad() {
        super.viewDidLoad()

        let textfield = UITextField(frame: CGRectMake(20, 100, 300, 44))
        //make some customization, if you want
        self.view.addSubview(textfield)

        textfield.delegate = self;
    }
}

extension ExampleVC: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        return string.characters.count > 0 ? numbers.contains(string) : true
    }
}

答案 12 :(得分:-1)

以下是 swift 4

的工作示例
COMM.write('AT' + '\r')

答案 13 :(得分:-1)

在文本字段中仅输入数值的另一个选项是选择相应文本字段的键盘类型属性。附上屏幕截图以供参考。Number Pad Selection