如何在Swift 2.0中的UITextfield中仅允许某些数字集 [英] How to allow only certain set of numbers in a UITextfield in swift 2.0

查看:73
本文介绍了如何在Swift 2.0中的UITextfield中仅允许某些数字集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UITextField,其中我将月份号作为输入.我成功地将UITextField中的字符数限制为2个.但是我希望用户仅输入1 to 12中的值,而不能输入其他值.当用户键入数字,即在func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool中时,必须同时完成此操作.如果我使用简单的if条件检查每个字符并在else部分返回false,则文本字段将不允许我使用clear或重新键入其他任何字符.谁来帮帮我.

I am having a UITextField in which i get the month number as input. I am successful in limiting the no of characters to 2 in the UITextField. But i want users to enter only the values from 1 to 12 and none other than that. This has to be done simultaneously when the user types the numbers i.e in func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool. If i use a simple if condition to check the each character and return false in else part the textfield won't allow me to use clear or retype any other character. someone help me.

推荐答案

将键盘类型设置为数字键盘

Set keyboard type as Number Pad

添加此

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

    if let text = textField.text {

        let newStr = (text as NSString)
            .stringByReplacingCharactersInRange(range, withString: string)
        if newStr.isEmpty {
            return true
        }
        let intvalue = Int(newStr)
        return (intvalue >= 0 && intvalue <= 12)
    }
    return true
}

这篇关于如何在Swift 2.0中的UITextfield中仅允许某些数字集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆