#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *phonetext;
@property (weak, nonatomic) IBOutlet UITextField *passwdtext;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//点击事件的监听
[phonetext addTarget:self action:@selector(textValueChanged) forControlEvents:UIControlEventEditingChanged];
[passwdtext addTarget:self action:@selector(textValueChanged) forControlEvents:UIControlEventEditingChanged];
}
- (void)textValueChanged
{
// self.loginBtn.enabled = (self.nameView.text.length != 0 && self.pwdView.text.length != 0);
if(![phonetext.text isEqual:@""] && ![passwtext.text isEqual:@""]){
[loginBtn setBackgroundImage:[UIImage imageNamed:@"login_background_usable"] forState:UIControlStateNormal];
}else{
[loginBtn setBackgroundImage:[UIImage imageNamed:@"login_background_unusable"] forState:UIControlStateNormal];
}
}
@end
//KVO监听
- (void)viewDidLoad {
[super viewDidLoad];
//KVO
[phonetext addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
[passwdtext addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
}
/**
* kvo回调
*
*/
- (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);
if(![phonetext.text isEqual:@""] && ![passwtext.text isEqual:@""]){
[loginBtn setBackgroundImage:[UIImage imageNamed:@"login_background_usable"] forState:UIControlStateNormal];
}else{
[loginBtn setBackgroundImage:[UIImage imageNamed:@"login_background_unusable"] forState:UIControlStateNormal];
}
}
//移除KVO
- (void)dealloc
{
[phonetext removeObserver:self forKeyPath:@"text"];
[passwdtext removeObserver:self forKeyPath:@"text"];
}
//通知
//通知
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//注册通知
[centeraddObserver:self selector:@selector(textValueChanged:) name:UITextFieldTextDidChangeNotification object:passwdtext];
[centeraddObserver:self selector:@selector(textValueChanged:) name:UITextFieldTextDidChangeNotification object:phonetext];
///监听文本框的值的改变
- (void)textValueChanged:(NSNotification*)notice
{
if(![phonetext.text isEqual:@""] && ![passwtext.text isEqual:@""]){
[loginBtn setBackgroundImage:[UIImage imageNamed:@"login_background_usable"] forState:UIControlStateNormal];
}else{
[loginBtn setBackgroundImage:[UIImage imageNamed:@"login_background_unusable"] forState:UIControlStateNormal];
}
}
//移除通知
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
网友评论