iPad没有像iPhone/iPod那样的"数字键盘"键盘.

我正在寻找如何将用户键盘限制为只接受从0到9的值.

我可以想象使用UITextField的"shouldChangeCharactersInRange",但我不知道实现它的最佳方式.

推荐答案

这就是您在SSN验证字段上处理问题的方式,如果需要,您可以修改最大长度并删除判断键盘类型的if语句.

还有一种逻辑可以在用户键入而不是粘贴数据时 suppress 最大长度alert .

在这段代码的上下文中,presentAlert()/presentAlert:只是一些基本函数,它使用传递的消息字符串表示UIAlertController(或传统UIAlertView).

SWIFT 5

// NOTE: This code assumes you have set the UITextField(s)'s delegate property to the 
// object that will contain this code, because otherwise it would never be called.
//
// There are also some better stylistic approaches in Swift to avoid all the 
// nested statements, but I wanted to keep the styles similar to allow others 
// to contrast and compare between the two languages a little easier.

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

    // Handle backspace/delete
    guard !string.isEmpty else {

        // Backspace detected, allow text change, no need to process the text any further
        return true
    }

    // Input Validation
    // Prevent invalid character input, if keyboard is numberpad
    if textField.keyboardType == .numberPad {

        // Check for invalid input characters
        if CharacterSet(charactersIn: "0123456789").isSuperset(of: CharacterSet(charactersIn: string)) {

            // Present alert so the user knows what went wrong
            presentAlert("This field accepts only numeric entries.")

            // Invalid characters detected, disallow text change
            return false
        }
    }

    // Length Processing
    // Need to convert the NSRange to a Swift-appropriate type
    if let text = textField.text, let range = Range(range, in: text) {

        let proposedText = text.replacingCharacters(in: range, with: string)

        // Check proposed text length does not exceed max character count
        guard proposedText.count <= maxCharacters else {

            // Present alert if pasting text
            // easy: pasted data has a length greater than 1; who copy/pastes one character?
            if string.count > 1 {

                // Pasting text, present alert so the user knows what went wrong
                presentAlert("Paste failed: Maximum character count exceeded.")
            }

            // Character count exceeded, disallow text change
            return false
        }

        // Only enable the OK/submit button if they have entered all numbers for the last four
        // of their SSN (prevents early submissions/trips to authentication server, etc)
        answerButton.isEnabled = (proposedText.count == 4)
    }

    // Allow text change
    return true
}

目标-C

// NOTE: This code assumes you have set the UITextField(s)'s delegate property to the 
// object that will contain this code, because otherwise it would never be called.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    // Handle backspace/delete
    if (!string.length)
    {
        // Backspace detected, allow text change, no need to process the text any further
        return YES;
    }

    // Input Validation
    // Prevent invalid character input, if keyboard is numberpad
    if (textField.keyboardType == UIKeyboardTypeNumberPad)
    {
        if ([string rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet].invertedSet].location != NSNotFound)
        {
            [self presentAlert: @"This field accepts only numeric entries."];
            return NO;
        }
    }

    // Length Validation
    NSString *proposedText = [textField.text stringByReplacingCharactersInRange:range withString:string];

    // Check proposed text length does not exceed max character count
    if (proposedText.length > maxCharacters)
    {
        // Present alert if pasting text
        // easy: pasted data has a length greater than 1; who copy/pastes one character?
        if (string.length > 1)
        {
            // Pasting text, present alert so the user knows what went wrong
            [self presentAlert: @"Paste failed: Maximum character count exceeded."];
        }

        // Character count exceeded, disallow text change
        return NO;
    }

    // Only enable the OK/submit button if they have entered all numbers for the last four
    // of their SSN (prevents early submissions/trips to authentication server, etc)
    self.answerButton.enabled = (proposedText.length == maxCharacters);

    // Allow text change
    return YES;
}

Ios相关问答推荐

如何正确测试后台URLSessionDownloadTask?

UIBezierPath包含:方法不检测到厚度大于1像素的线上的touch

带外部笔划的圆形进度视图

如何使视图完全适合屏幕,而不会在旋转时溢出手机屏幕的边界?

通过在SWIFT中不起作用的泛型传递协议一致性类型

在 SwiftUI 中以编程方式插入内嵌图像

Strange UIView.animate更改UIButton标题 colored颜色 的行为

从 PHAssets 生成图像时,iOS 应用程序因内存问题而崩溃

如何在 SwiftUI 中创建两个大小相同的正方形占据整个屏幕宽度?

Swift 共享数据模型在页面之间进行通信.这个怎么运作

如何以编程方式调用视图控制器?

导航控制器自定义过渡动画

Xcode 4 + iOS 4.3:存档类型不存在打包程序

UICollectionView flowLayout 没有正确包装单元格

正确使用 Alamofire 的 URLRequestConvertible

如何使用完成按钮制作 UIPickerView?

iTunes Connect 中的无限制 Web 访问是什么意思

如何在 Android 和 iPhone 的移动应用程序中实施推荐计划

UIView - 加载视图时如何获得通知?

Flutter:如何创建一个新项目