我需要一种方法来禁用保存按钮,直到所有必需的文本框中都输入了文本?我正在开发Swift中的应用程序,我已经在Objective-c中找到了很多答案。因为我现在完全掌握了Objective-c的知识,所以我无法弄清楚它的意思。
有没有人有可以在Swift中完成的解决方案?
我知道如何启用/禁用按钮。我还知道如何检查文本字段是否为空。我只是不确定如何创建它,以便我的代码总是检查它是否为空。我尝试了一次while循环,但正如我所料,这会冻结一切。
发布于 2015-07-28 10:10:09
列出实现这一目标的方法之一:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var button: UIButton!
//Need to have the ViewController extend UITextFieldDelegate for using this feature
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// Find out what the text field will be after adding the current edit
let text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
if !text.isEmpty{//Checking if the input field is not empty
button.userInteractionEnabled = true //Enabling the button
} else {
button.userInteractionEnabled = false //Disabling the button
}
// Return true so the text field will be changed
return true
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Setting the Delegate for the TextField
textField.delegate = self
//Default checking and disabling of the Button
if textField.text.isEmpty{
button.userInteractionEnabled = false // Disabling the button
}
}
}发布于 2015-04-05 00:01:01
尽管到目前为止给出了所有的评论,为了不进一步破坏评论区,我试着给出一些关于如何解决你的问题的提示:
didEndEditing方法,并在该方法中迭代outlet集合以检查每个文本字段的输入请注意,这只是实现这一点的一种方法,但您可能会明白这一点。
发布于 2015-04-04 23:54:30
使用文本字段的委托方法(或目标操作模式)检查用户继续操作所需的条件。如果满足这些条件,请启用该按钮。
https://stackoverflow.com/questions/29448185
复制相似问题