Swift - 验证 UITextField [英] Swift - validating UITextField

查看:37
本文介绍了Swift - 验证 UITextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用中有这些插座:

I have these outlets in my app:

@IBOutlet var name1: UITextField!

@IBOutlet var name2: UITextField!

@IBOutlet var name3: UITextField!

@IBOutlet var name4: UITextField!

@IBOutlet var newButton: UIButton!

我尝试做的是以下内容:

What I tried to do is the following:

每次用户在这四个 UITextField 之一中输入内容或删除内容时,我想检查是否有任何 UITextField 为空

Every time the user types something in one of these four UITextFields or deletes something, I want to check if any UITextField is empty

如果任何 UITextField 为空,则该按钮应该被禁用.

If any UITextField is empty, the button should be disabled.

如果所有 UITextField 都设置了(非空),按钮应该被启用.

If all UITextFields are set (not empty), the button should be enabled.

我的代码:

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

    setButton()

    return true
}

func setButton() {

    let inputValid = checkInput()

    if inputValid {

        newButton.enabled = true

    } else {

        newButton.enabled = false

    }

}

func checkInput() -> Bool {

    let name1Value = name1.text
    let name2Value = name2.text
    let name3Value = name3.text
    let name4Value = name4.text

    if !name1Value.isEmpty && !name2Value.isEmpty && !name3Value.isEmpty && !name4Value.isEmpty {

        return true

    }

    return false

}

好的,它现在可以工作 50%.

Ok, it works 50% for now.

当我在每个 UITextField 中输入一个字符时,按钮仍然被禁用.

When I type one character in each UITextField, the button is still disabled.

当我向任何 UITextField 添加第二个时,按钮被启用等...

When I add a second one to any UITextField, the button gets enabled etc...

谁能帮我解决这个问题?

Can anyone help me with this?

推荐答案

或者,您可以使用这个,每次按下一个键时都会调用它:

Alternatively, you can use this, which is called every time a key is pressed:

name1.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
name2.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
name3.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
name4.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)


func textFieldDidChange(textField: UITextField) {
    if name1.text?.isEmpty || name2.text?.isEmpty || name3.text?.isEmpty || name4.text?.isEmpty {
        //Disable button
    } else {
        //Enable button
    }
}

这篇关于Swift - 验证 UITextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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