如何在swift中设置textfield的范围

时间:2015-12-16 07:23:57

标签: swift2

我有2个文本字段接受MM格式化月份,YYYY格式化年份。我想将范围设置为文本字段,以便月份文本字段只接受值格式01-12,年份应接受有效的四位数年份。

我使用了以下代码,但还不足以将范围设置为月

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
    let maxLength = 4
    let currentString: NSString = textField.text
    let newString: NSString =
             currentString.stringByReplacingCharactersInRange(range, withString: string)
    return newString.length <= maxLength
}

1 个答案:

答案 0 :(得分:1)

设置月份文本字段标记2(必需最大长度)和年份文本字段标记4(所需最大长度),并在shouldChangeCharactersInRange方法中添加以下代码

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
    {
        let maxLength = textField.tag // dynamic tag form IB
        var isAllow:Bool = true
        isAllow = NSCharacterSet.alphanumericCharacterSet().isSupersetOfSet(NSCharacterSet(charactersInString: string))
        if (isAllow && ((range.location < maxLength && (range.length == 0) && (((textField.text?.characters.count)! + string.characters.count) <= maxLength)) || ((range.length > 0) && (((string.characters.count + (textField.text?.characters.count)!) - range.length) <= maxLength)))) {
            if  textField.tag == 2 && string.characters.count > 0 && textField.text?.characters.count > 0 { //condition for month text field
                let newString: NSString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
                return newString.integerValue >= 1 && newString.integerValue <= 12
            }
            //you can any custom conditions for year text field also
            return true;
        } else {
            return false;
        }
    }