简体   繁体   English

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

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

I want to limit the user's option in the textfield to type only numbers that is less than 59. 我想将用户在文本字段中的选项限制为仅键入小于59的数字。

Iv'e got a code that works perfectly on only 1 textfield: 我有一个代码只能在1个文本字段上完美运行:

func textField(textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String) -> Bool
{
    var startString = ""
    if (minutesTF.text != nil)
    {
        startString += minutesTF.text!
    }
    startString += string
    var limitNumber = startString.toInt()
    if limitNumber > 59
    {
        return false
    }
    else
    {
        return true
    }
}

But my code for 2 textfields does't work right: 但是我的2个文本字段的代码无法正常工作:

func textField(textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String) -> Bool
{
    var startString = ""
    if (minutesTF.text != nil)
    {
        startString += minutesTF.text!
    }
    startString += string
    var limitNumber = startString.toInt()
    if limitNumber > 59
    {
        return false
    }
    else
    {
        return true
    }
}
func textField2(textField: UITextField,
    shouldChangeCharactersInRange range: NSRange,
    replacementString string: String) -> Bool
{
    var startString = ""
    if (secondsTF.text != nil)
    {
        startString += secondsTF.text!
    }
    startString += string
    var limitNumber = startString.toInt()
    if limitNumber > 59
    {
        return false
    }
    else
    {
        return true
    }
}

You can only have one implementation of the shouldChangeCharactersInRange method. 您只能具有shouldChangeCharactersInRange方法的一种实现。 So your second one (with the textField2 name in the method) is never called. 因此,永远不会调用您的第二个(在方法中使用textField2名称)。 Delete your textField2:shouldChangeCharactersInRange:replacementString: method. 删除您的textField2:shouldChangeCharactersInRange:replacementString:方法。

Note that the text field is passed as a parameter. 请注意,文本字段作为参数传递。 Use that text field parameter instead of hardcoding the text field ivar in your implementation. 使用该文本字段参数,而不是在实现中对文本字段ivar进行硬编码。

In other words, replace the use of minutesTF with textField . 换句话说,用textField代替minutesTF使用。

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 > 59
    {
        return false
    }
    else
    {
        return true
    }
}

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

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