监听文本框的开始编辑和结束编辑状态来修改占位文字颜色

1、第一种:由于UITextfield继承自UIControl,所有可以通过addTarget来监听

[self addTarget:self action:@selector(editingDidBegin) forControlEvents:UIControlEventEditingDidBegin]; [self addTarget:self action:@selector(editingDidEnd) forControlEvents:UIControlEventEditingDidEnd];

- (void)editingDidBegin { //TODO}

- (void)editingDidEnd { //TODO}

2、第二种:通过通知实现(记得要移除通知)

[[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代理来实现,不过不推荐这种写法,因为可以设置多个代理,而且代理通常是别人而非自己。

4、第四种:利用内部特性实现

- (BOOL)becomeFirstResponder {

[self setValue:[UIColor whiteColor] forKeyPath:PlaceholderColorKey];

return [super becomeFirstResponder];

}

-(BOOL)resignFirstResponder {

[self setValue:[UIColor grayColor] forKeyPath:PlaceholderColorKey];

return [super resignFirstResponder];

}

你可能感兴趣的:(监听文本框的开始编辑和结束编辑状态来修改占位文字颜色)