简体   繁体   English

如何限制Swift文本字段中的数字?

[英]How to limit the numbers in the text field in Swift?

I want the user to fill in the textfield a number from 0 to 60. How can i limit the number chars to 2? 我希望用户在文本字段中填写0到60之间的数字。如何将数字字符数限制为2? How to limit the maximum number to 60? 如何将最大数量限制为60? And how to cancel the 'paste' option on the textfield so the user won't be able to paste letters? 以及如何取消文本字段上的“粘贴”选项,以便用户无法粘贴字母?

I think there are 2 ways you can do that. 我认为有两种方法可以做到这一点。

Implement the UITextFieldDelegate and implement function 实现UITextFieldDelegate并实现函数

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

    var startString = ""

    if textField.text != nil {
        startString += textField.text!
    }

    startString += string

    var limitNumber = startString.toInt()

    if limitNumber > 60 {
        return false
    } else {
        return true
    }
}

In this Each time check what has been entered to the UITextField so far, convert to Integer and if the new value is higher than 60, return false. 在此每次检查到目前为止输入到UITextField ,转换为Integer,如果新值高于60,则返回false。 (Also show the appropriate error to the user). (还向用户显示相应的错误)。

I think a much better way would be to provide UIPickerView . 我认为更好的方法是提供UIPickerView

Use textfield's delegate method 使用textfield的委托方法

Where 10 is Max limit for text field... 其中10是文本字段的最大限制...

      func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let newLength = countElements(textField.text) + countElements(string) - range.length
       return newLength <= 10 // Bool
 }

If countElements not work in latest version of s wift use count instead of countElements. 如果countElements不能在最新版本的s wift中使用count而不是countElements。

To disable copy and paste: 要禁用复制和粘贴:

func canPerformAction(_ action: Selector, withSender sender: AnyObject?) -> Bool
{
    if action == "paste:"
        {return false}
    return super.canPerformAction(action,withSender:sender)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM