31

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

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

14 回答 14

58

在您从中获取这些值的任何 UITextField 中,您都可以指定当有人在文本字段内触摸时要显示的键盘类型。

EG 纯数字键盘。

像这个截图:

将出现仅数字键盘

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

要过滤掉标点符号,请设置文本字段的委托并设置 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;
}
于 2012-05-24T09:45:56.653 回答
26

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

斯威夫特 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
}
于 2014-03-14T11:22:41.020 回答
10
[textField setKeyboardType:UIKeyboardTypeNumberPad];
于 2012-05-24T09:47:09.863 回答
9

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

  1. 检查允许的最大字符数。
  2. 检查有效的十进制数。
  3. 只检查数字

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

  1. self.maxCharacters
  2. self.numeric// 只有int字符。
  3. self.decimalNumeric// 只有数字和“.”、“”(对于特定的语言环境,如俄语)。

代码:

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

演示:

在此处输入图像描述

于 2015-06-04T12:51:21.243 回答
7

修改后的 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;
}
于 2015-07-29T03:02:55.927 回答
3

迅速 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
  }
}
于 2019-01-02T10:32:44.217 回答
2

这是斯威夫特的解决方案:

在 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
}
于 2015-11-25T09:36:56.233 回答
1

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

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

在提交按钮上检查它。

于 2012-05-24T09:48:26.150 回答
1

这个答案在 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
}
于 2017-04-19T14:34:50.967 回答
0

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

yourTxtField.delegate = self;

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

- (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 函数替换为以下内容:

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”代表字符的限制。

干杯! :)

于 2015-09-04T23:13:17.307 回答
0

@almas-adlibek 最佳答案的 Swift 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;
}
于 2018-10-17T22:49:42.753 回答
-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
    }
}
于 2016-11-17T22:23:59.297 回答
-1

仅在文本字段中输入数值的另一种选择是选择相应文本字段的键盘类型属性。附上截图供参考。数字键盘选择

于 2018-03-26T13:05:56.053 回答
-2

这是swift 4的工作示例

public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
{
    // Allow Backspace
    if string.count == 0 {
        return true
    }

    // Allow Only Valid Decimal Numbers
    if let textFieldText = textField.text   {

        let finalText = (textFieldText as NSString).replacingCharacters(in: range, with: string)
        if Double(finalText) != nil {
            return true
        }
    }
    return false
}
于 2017-12-25T12:15:29.693 回答