UI按钮背景颜色和按钮启用/禁用

时间:2017-11-07 07:10:25

标签: swift3

如何在按钮值为#88D317的背景中设置十六进制值?此外,我希望仅在文本字段中存在文本时才启用按钮,否则禁用。

这是我写的代码:

class ViewControllerDonarLogin: UIViewController, UITextFieldDelegate {
    @IBOutlet var btnlogin: UIButton!
    @IBOutlet weak var btn: UIButton!
    @IBOutlet weak var textfieldpassword: UITextField!
    @IBOutlet weak var textfieldusername: UITextField!

    var alert : UIAlertController = UIAlertController()
    var action : UIAlertAction = UIAlertAction()

    override func viewDidLoad() {
        super.viewDidLoad()

        buttonborder()

        btnlogin.backgroundColor = UIColor(red: 136/255, green: 211/255, blue: 23/255, alpha: 0.5)

        if textfieldpassword.text == "" && textfieldusername.text == "" {
            btnlogin.isEnabled = false
        } else {
            btnlogin.isEnabled = true
        }
        // Do any additional setup after loading the view.
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用其中一个文字字段的make(1)操作。

UIControl中,添加viewDidLoad作为self的目标:

editingChanged

现在,添加此方法:

textfieldpassword.addTarget(self, action: #selector(textChanged), for: .editingChanged)
textfieldusername.addTarget(self, action: #selector(textChanged), for: .editingChanged)

将您在func textChanged() { // This will be called every time the text field's text changes } 中编写的原始代码移至上述方法。

viewDidLoad

答案 1 :(得分:0)

您希望通过使用文本字段委托来实现。你必须使用

func textFieldDidEndEditing(_ textField: UITextField) {
     if textfieldpassword.text == "" || textfieldusername.text == "" {
        btnlogin.isEnabled = false
    } else {
        btnlogin.isEnabled = true
    }
}

您还必须在viewDidLoad中禁用该按钮:

override func viewDidLoad() {
    super.viewDidLoad()
    btnlogin.isEnabled = false // as you want button to be disabled at the starting 
}