我通过拖拽生成了一个文本框和一个按钮,我希望实现的功能是
“文本框输入为空时,按钮禁用,文本框输入不空时,按钮可用”
我使用的方式是用一个动作绑定与文本框编辑有关的事件,其中inputField代表文本框,primeFactorizationButton代表按钮
@IBAction func changeButton(_ sender: AnyObject) {
if(inputField.text == ""){
primeFactorizationButton.isUserInteractionEnabled=false
}
else{
primeFactorizationButton.isUserInteractionEnabled=true
}
}
但是这种方法仍然不好用,好像实际上的需要是实时监听文本框的值,inputField.text,实时调整 button 的可用状态,请问我应该怎么修改代码呢?
Method 1: Set inputField.delegate. Calculate the final text in
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
and determine whether to disable the button based on text.length.Method 2: Listen for notification
UITextFieldTextDidChangeNotification
,NSNotificationCenter.defaultCenter.addObserver
时object
Pass your inputField, and then judge in the processing method:I just happened to achieve this function recently, and it is quite easy to do. First, comply with the proxy agreement of UITextFIeld and implement the following method:
Then create a notification and make a judgment in the notification’s listening method:
But remember to remove the notification:
There is another way to use RAC, reactive programming, which is more convenient, but I don’t know how to do it yet, you can also try it
Complement an elegant