在相同的文本字段功能swift

发布时间: 2016/5/23 23:05:56
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有两个完全相同的功能在我的 ViewController,看来他们俩都不能被重命名。

第一个用来限制字符并显示左的数字。

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

        if let textField = textField as? UITextField {

        if (range.length + range.location > textField.text!.characters.count) {
                return false;
        }

        let newLength = textField.text!.characters.count + string.characters.count - range.length;
        cLabel.text =  String(25 - newLength)
        return newLength <= 25 // To just allow up to … characters

        }
    return true;
    }

第二个使按钮文本添加到同一文本字段时。

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

        // Find out what the text field will be after adding the current edit
        let text = (ahskField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

        if text.isEmpty{//Checking if the input field is not empty
            ahskButton.userInteractionEnabled = false //Enabling the button
            ahskButton.enabled = false
        } else {
            ahskButton.userInteractionEnabled = true //Disabling the button
            ahskButton.enabled = true
        }

        // Return true so the text field will be changed
        return true
    }

有一种结合他们或任何东西吗?

解决方法 1:

你只需要一个 shouldChangeCharactersInRange 函数。

把所有您的逻辑放在一个方法中。

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

    // Find out what the text field will be after adding the current edit
    let text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
    let newLength = text.characters.count
    if newLength <= 25 {
        cLabel.text = String(25 - newLength)
        if text.isEmpty { //Checking if the input field is not empty
            ahskButton.userInteractionEnabled = false //Enabling the button
            ahskButton.enabled = false
        } else {
            ahskButton.userInteractionEnabled = true //Disabling the button
            ahskButton.enabled = true
        }

        return true;
    } else {
        return false;
    }
}
赞助商