监听文本输入框内容值的改变——4种方法

以下是addTarget:

import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *nameView;
@property (weak, nonatomic) IBOutlet UITextField *pwdView;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];

    [self.nameView addTarget:self action:@selector(textValueChanged) forControlEvents:UIControlEventEditingChanged];
    [self.pwdView addTarget:self action:@selector(textValueChanged) forControlEvents:UIControlEventEditingChanged];
    }

  • (void)textValueChanged
    {
    self.loginBtn.enabled = (self.nameView.text.length != 0 && self.pwdView.text.length != 0);
    }

@end
以下是通知:
通知

  • (void)viewDidLoad {
    [super viewDidLoad];
    //创建通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //注册通知
    [center addObserver:self selector:@selector(textValueChanged:) name:UITextFieldTextDidChangeNotification object:self.nameView];
    [center addObserver:self selector:@selector(textValueChanged:) name:UITextFieldTextDidChangeNotification object:self.pwdView];

}
//监听文本框的值的改变

  • (void)textValueChanged:(NSNotification *)notice
    {
    self.loginBtn.enabled = (self.nameView.text.length != 0 && self.pwdView.text.length != 0);
    }
    //移除通知

  • (void)dealloc
    {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    以下是KVO:

  • (void)viewDidLoad {
    [super viewDidLoad];
    //KVO

    [self.nameView addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
    [self.pwdView addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];

}
/**

  • kvo回调

*/

  • (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
    self.loginBtn.enabled = (self.pwdView.text.length != 0 && self.nameView.text.length != 0);
    }

//移除KVO

  • (void)dealloc
    {
    [self.nameView removeObserver:self forKeyPath:@"text"];
    [self.pwdView removeObserver:self forKeyPath:@"text"];
    }
    以下是EditingChanged:
    /**
  • 监听登录文本框的输入
    */
  • (IBAction)nameViewChange
    {
    self.loginBtn.enabled = (self.nameView.text.length != 0 && self.pwdView.text.length != 0);
    }
    /**
  • 登录密码输入框的输入
    */
  • (IBAction)pwdViewChange
    {
    self.loginBtn.enabled = (self.nameView.text.length != 0 && self.pwdView.text.length != 0);
    }
    这个在连线的时候,选择的是EditingChanged 这个方法

你可能感兴趣的:(监听文本输入框内容值的改变——4种方法)