1、第一種:由于UITextfield繼承自UIControl呛梆,所有可以通過addTarget來監(jiān)聽
[self addTarget:self action:@selector(editingDidBegin) forControlEvents:UIControlEventEditingDidBegin]; [self addTarget:self action:@selector(editingDidEnd) forControlEvents:UIControlEventEditingDidEnd];
- (void)editingDidBegin { //TODO}
- (void)editingDidEnd { //TODO}
2挑格、第二種:通過通知實現(xiàn)(記得要移除通知)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editingDidBegin) name:UITextFieldTextDidBeginEditingNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editingDidEnd) name:UITextFieldTextDidEndEditingNotification object:nil];
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)editingDidBegin {
[self setValue:[UIColor whiteColor] forKeyPath:PlaceholderColorKey];
}
- (void)editingDidEnd {
[self setValue:[UIColor grayColor] forKeyPath:PlaceholderColorKey];
}
3讨勤、第三種:還可以通過UITextfieldDelegate代理來實現(xiàn),不過不推薦這種寫法瑞佩,因為可以設(shè)置多個代理掏父,而且代理通常是別人而非自己淆储。
4冠场、第四種:利用內(nèi)部特性實現(xiàn)
- (BOOL)becomeFirstResponder {
[self setValue:[UIColor whiteColor] forKeyPath:PlaceholderColorKey];
return [super becomeFirstResponder];
}
-(BOOL)resignFirstResponder {
[self setValue:[UIColor grayColor] forKeyPath:PlaceholderColorKey];
return [super resignFirstResponder];
}