gpt4 book ai didi

ios - 如何在 UITextfield 数据为空或已填充时禁用/启用按钮?

转载 作者:搜寻专家 更新时间:2023-11-01 07:17:20 25 4
gpt4 key购买 nike

Output Console

这是我的功能。正如您在上面看到的,当文本字段为空(或 nil)并且按钮被禁用时,我能够在控制台中收到一条消息。但是,当在我的文本字段中输入数据时,我没有收到回复。如果有人可以帮助我解决这个问题或类似的问题,我将不胜感激。

func logicDataCheck() {
let textfield: Array<Bool?> = [lastNameTextField.text?.isEmpty, phoneNumberTextField.text?.isEmpty, firstNameTextField.text?.isEmpty]

if (textfield[0]! || textfield [1]! || textfield [2]!)
{
print("Textfield is empty")
continue_Button.isEnabled = false
continue_Button.alpha = 0.5
}
else
{
if (textfield[0]! || textfield [1]! || textfield [2]!) {
print("Textfield is full")
continue_Button.isEnabled = true
continue_Button.alpha = 1
}
}
}

最佳答案

在您的 viewDidLoad 中,您可以添加以下行:

configureTextFields()
// you'll need to call updateTextField() when the view loads the first time.
// After the configureTextFields() adds targets, it'll get called when editing changes
updateTextField()

此外,添加这些方法:

func configureTextFields() {
// create an array of textfields
let textFieldArray = [firstNameTextField, lastNameTextField, phoneNumberTextField]

// configure them...
for textField in textFieldArray {
// make sure you set the delegate to be self
textField?.delegate = self
// add a target to them
textField?.addTarget(self, action: #selector(ViewController.updateTextField), for: .editingChanged)
}
}

// this is the target that gets called when editing changes
func updateTextField() {
// create an array of textFields
let textFields = [firstNameTextField, lastNameTextField, phoneNumberTextField]
// create a bool to test if a textField is blank in the textFields array
let oneOfTheTextFieldsIsBlank = textFields.contains(where: {($0?.text ?? "").isEmpty})
if oneOfTheTextFieldsIsBlank {
continueButton.isEnabled = false
continueButton.alpha = 0.5
} else {
continueButton.isEnabled = true
continueButton.alpha = 1.0
}
}

您需要让您的 ViewController 采用 UITextFieldDelegate 协议(protocol)。你可以这样做:

class ViewController: UIViewController, UITextFieldDelegate {
// the code inside your view controller
}

这里是一个链接 demo I created on GitHub

关于ios - 如何在 UITextfield 数据为空或已填充时禁用/启用按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41420116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com