禁用/启用Xcode中的按钮

时间:2018-04-29 05:16:28

标签: ios swift xcode xcode8 swift4

嗨,我是Swift编程的新手。 我想要做的是在viewDidLoad中禁用我的按钮(signIn),并仅在文本字段中包含文本时启用。这是我到目前为止所取得的成就。 (虽然不多!)

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    signIn.isEnabled = false

    // Do any additional setup after loading the view, typically from a nib.
}

@IBOutlet weak var emailtxt: UITextField!
@IBOutlet weak var passwordtxt: UITextField!
@IBOutlet weak var signIn: UIButton!

我需要帮助才能在signIn中创建一个函数,该按钮会保持按钮被禁用,直到文本字段(emailtxt& passwordtxt)中包含文本然后继续。

如果有人能给我打电话,我很高兴。 提前谢谢!

4 个答案:

答案 0 :(得分:2)

ViewController设为emailtxtpasswordtxt的代表,

override func viewDidLoad() {
    super.viewDidLoad()
    signIn.isEnabled = false

    emailtxt.delegate = self
    passwordtxt.delegate = self 

    // Do any additional setup after loading the view, typically from a nib.
}

符合您的ViewControllerUITextFieldDelegate,并在文字输入完成后启用/停用

extension ViewController: UITextFieldDelegate {

    func textFieldDidEndEditing(_ textField: UITextField) {
        if emailtxt.text?.isEmpty == false && passwordtxt.text?.isEmpty == false {
            signIn.isEnabled = true
        } else {
            signIn.isEnabled = false
        }
    }
}

以下是您共享的代码的修复程序。

import UIKit
extension UIViewController {

    func hideKeyboardWhenTappedAround() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }

    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}

extension SignInVC: UITextFieldDelegate {

    func textFieldDidEndEditing(_ textField: UITextField) {
        if emailtxt.text?.isEmpty == false && passwordtxt.text?.isEmpty == false {
            signIn.isEnabled = true
        } else {
            signIn.isEnabled = false
        }
    }
}
class SignInVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        signIn.isEnabled = false
        emailtxt.delegate = self
        passwordtxt.delegate = self
        self.hideKeyboardWhenTappedAround()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBOutlet weak var emailtxt: UITextField!
    @IBOutlet weak var passwordtxt: UITextField!
    @IBOutlet weak var signIn: UIButton!
}

答案 1 :(得分:1)

使用 SwiftValidator

https://github.com/SwiftValidatorCommunity/SwiftValidator

这样,您将设置电子邮件和验证;密码如下

import SwiftValidator

let validator = Validator()

validator.registerField(emailTextField, errorLabel: emailErrorLabel, rules: [RequiredRule(), EmailRule(message: "Invalid email")])




// MARK: - ValidationDelegate
extension ViewController: ValidationDelegate {
    func validationSuccessful() {
        self.loginUser()
    }

    func validationFailed(_ errors:[(Validatable ,ValidationError)]) {
        for (field, error) in errors {

//Handle as per need - show extra label - shake view etc
/*
            if let field = field as? UITextField {
                Utilities.shakeTheView(shakeView: field)
            }
            error.errorLabel?.text = error.errorMessage
            error.errorLabel?.isHidden = false
*/
        }
    }
}

答案 2 :(得分:1)

首先在viewDidLoad()

中为所有textField添加这些内容
    emailtxt.addTarget(self, action: #selector(textFieldDidChange(_:)),
                        for: UIControlEvents.editingChanged)
   passwordtxt.addTarget(self, action: #selector(textFieldDidChange(_:)),
                        for: UIControlEvents.editingChanged)

然后使用:

@objc func textFieldDidChange(_ textField: UITextField) {
    self.buttonIsEnabled()
}

func buttonIsEnabled() {
    var buttonIsEnabled = true

    defer {
        self.signIn.isEnabled = buttonIsEnabled
    }

    guard let emailtxt = self.emailtxt.text, !emailtxt.isEmpty  else {
        addButtonIsEnabled = false
        return
    }


    guard let passwordtxt = self. passwordtxt.text, ! passwordtxt.isEmpty  else {
        addButtonIsEnabled = false
        return
    }

}

我在我的代码中使用这种方式,效果很好。

即使您可以添加更多方法以便对buttonIsEnabled进行额外检查,例如:

self.checkEmailIsValid(for: emailtxt)

当然你应该在以下之前处理这个方法:

 func checkEmailIsValid(for: String) {
   //...
}

答案 3 :(得分:1)

我要做的是从您的某个文字字段创建IBAction,并将事件设置为Editing Changed

IBAction set to Editing Changed

代码应如下所示:

@IBAction func textFieldEditingDidChange(_ sender: UITextField) {

}

然后,您可以通过从插座拖动到剩余字段,将同一插座连接到两个文本字段。如果您已正确连接两者,单击IBAction左侧的圆圈应显示两个文本字段:

现在,只要字段 中的文字发生变化,就会触发此操作。

然后,在文件的顶部,我将创建一个返回false的计算属性,除非两个字段都有内容:

var shouldEnableButton: Bool {
    guard let text1 = textField1.text, let text2 = textField2.text else {
        return false
    }
    return text1.isEmpty && text2.isEmpty ? false : true
}

最后,我们将shouldEnableButton添加到我们的IBAction:

@IBAction func textFieldEditingDidChange(_ sender: UITextField) {
    button.isEnabled = shouldEnableButton
}

重要

当您将第二个文字字段连接到插座时,它会错误地指定 Editing Did End 作为其活动:

删除此活动,然后点击并从Editing Changed拖到您的IBAction: