我在哪里调用我的函数,以便它成功地更新我的UI



我编写了以下函数,以确保我的用户在能够继续之前填写textField。

func validateFields() -> String {

if textfield.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
return "Please fill in textField"
} 
return "A-OK."
}
func updateUI() {
let verdict = validateFields()
if verdict == "A-OK." {
self.buttonOne.alpha = 1
}
}

override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}

但是,一旦填写了textField,上面的代码就无法更新UI。我知道我错过了一些琐碎的事情,我只是无法理解什么。我真的很感激你的帮助。

根据您的要求使用texttextFieldDidEndEditing、textFieldDidBeginEditing、textFieldShouldReturn、等。

但我认为委托">textFieldShouldReturn"符合您的要求。

您只需要在此委托中添加函数updateUI((

您可以很容易地创建文本字段的出口viewDidLoad()方法中的自我委托

@IBOutlet var txtfld: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
txtfld.delegate = self
}
// UITextField Delegates
func textFieldDidBeginEditing(_ textField: UITextField) {
print("TextField did begin editing method called")
}
func textFieldDidEndEditing(_ textField: UITextField) {
print("TextField did end editing method called")
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
print("TextField should begin editing method called")
return true;
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
print("TextField should clear method called")
return true;
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
print("TextField should end editing method called")
return true;
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("While entering the characters this method gets called")
return true;
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
print("TextField should return method called")
textField.resignFirstResponder();
return true;
}
}

我建议在调用您的方法时,您应该使用updateUI()textFieldShouldReturn(_ textField: UITextField)中的函数方法

我想您可以很容易地将文本视图绑定到本地属性,并观察该属性上的更改。当所有内容都有效时,您可以启用buttonOne,并在将来的计算中使用该属性的值。

var myTextFieldData: String {
didSet {
updateUI()
}
}

此外,请记住,为了将textFieldmyTextFieldData:绑定,您还必须实现UITextField委托

textField.delegate = self
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
myTextFieldData = string
return true
}

最新更新