ios - 如何实现“文本框输入为空时,按钮禁用,文本框输入不空时,按钮可用”
怪我咯
怪我咯 2017-04-18 09:33:27
0
4
608

我通过拖拽生成了一个文本框和一个按钮,我希望实现的功能是
“文本框输入为空时,按钮禁用,文本框输入不空时,按钮可用”


我使用的方式是用一个动作绑定与文本框编辑有关的事件,其中inputField代表文本框,primeFactorizationButton代表按钮

@IBAction func changeButton(_ sender: AnyObject) {
        if(inputField.text == ""){
            primeFactorizationButton.isUserInteractionEnabled=false
        }
        else{
            primeFactorizationButton.isUserInteractionEnabled=true
        }
    }


但是这种方法仍然不好用,好像实际上的需要是实时监听文本框的值,inputField.text,实时调整 button 的可用状态,请问我应该怎么修改代码呢?

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(4)
Peter_Zhu

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 UITextFieldTextDidChangeNotificationNSNotificationCenter.defaultCenter.addObserverobject Pass your inputField, and then judge in the processing method:

self.actionButton.enabled = self.inputField.text.length > 0;
小葫芦

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:

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    self.nextButton.enabled = NO;
    self.nextButton.selected = NO;
    return YES;
}

Then create a notification and make a judgment in the notification’s listening method:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange) name:UITextFieldTextDidChangeNotification object:nil];
- (void)textFieldDidChange
{
    if (self.nameField.text.length == 0 || self.IDCardField.text.length == 0 || self.contactPhoneField.text.length == 0 || self.contactPhoneField.text.length < 11 || self.addressField.text.length == 0 || self.postcodeField.text.length == 0) {
        self.nextButton.enabled = NO;
        self.nextButton.selected = NO;
    } else {
        self.nextButton.enabled = YES;
        self.nextButton.selected = YES;
    }
}

But remember to remove the notification:

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

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

textField.addTarget(self, action: #selector(self.change(_:)), forControlEvents:.EditingChanged)
func change(textField1:UITextField){
        // 进行判断
    }
Peter_Zhu
self.inputField.addTarget(self, action: #selector(self.textFielDChanged), forControlEvents: UIControlEvents.EditingChanged)

func textFielDChanged() {
    self.actionButton.enabled = self.inputField.text.length > 0;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template