以下是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];
//創(chuàng)建通知
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];
}
//監(jiān)聽文本框的值的改變
(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回調(diào)
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)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:
/**
- 監(jiān)聽登錄文本框的輸入
*/
- (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 這個方法