Cre*_*ter 5 validation uitextfield swift
我在我的应用程序中有这个插座:
@IBOutlet var name1: UITextField!
@IBOutlet var name2: UITextField!
@IBOutlet var name3: UITextField!
@IBOutlet var name4: UITextField!
@IBOutlet var newButton: UIButton!
Run Code Online (Sandbox Code Playgroud)
我试图做的是以下内容:
每当用户在这四个文本字段之一中键入内容或删除某些内容时,我想检查是否有任何文本字段为空
如果任何文本字段为空,则应禁用该按钮.
如果设置了所有文本字段(非空),则应启用该按钮.
我的代码:
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
}
Run Code Online (Sandbox Code Playgroud)
好的,它现在可以使用50%.
当我在每个文本字段中键入一个字符时,该按钮仍处于禁用状态.
当我向任何文本字段添加第二个时,按钮被启用等...
有谁可以帮我这个?
问候和感谢!
bri*_*one 14
或者,你可以使用它,每次按下一个键时都会调用它:
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
}
}
Run Code Online (Sandbox Code Playgroud)
Swift 4- 这是我为避免长时间使用条件而解决的方法-与接受的答案不同,这还允许您对每个文本字段进行实时验证,可以根据用户键入的内容更新UI。
let textfields : [UITextField] = [name1, name2, name3, name4]
for textfield in textfields {
textfield.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
}
@objc func textFieldDidChange(_ textField: UITextField) {
//set Button to false whenever they begin editing
yourButton.isEnabled = false
guard let first = textFields[0].text, first != "" else {
print("textField 1 is empty")
return
}
guard let second = textFields[1].text, second != "" else {
print("textField 2 is empty")
return
}
guard let third = textFields[2].text, third != "" else {
print("textField 3 is empty")
return
}
guard let forth = textFields[3].text, forth != "" else {
print("textField 4 is empty")
return
}
// set button to true whenever all textfield criteria is met.
yourButton.isEnabled = true
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30156 次 |
| 最近记录: |