监听文本框事件几种方法总结

时间:2020-11-28 14:54:54
  • // 占位文字颜色
    #define LSLPlaceholderColorKey @"placeholderLabel.textColor"
    // 默认的占位文字颜色
    #define LSLPlaceholderDefaultColor [UIColor grayColor]
    // 聚焦的占位文字颜色
    #define LSLPlaceholderFocusColor [UIColor whiteColor]
    
  • 实现对输入框的事件监听的4中方法
    • 方法1,用代理实现,这种方式不推荐,因为delegate实现很容易被外界覆盖
@interface LSLLoginRegisterTextFiled()<UITextFieldDelegate>
@end

@implementation LSLLoginRegisterTextFiled
- (void)awakeFromNib
{
    // 方法1,用代理实现,这种方式不推荐,因为delegate实现很容易被外界覆盖
    self.delegate = self;
}

#pragma mark - (方法1,用代理实现)实现UITextFieldDelegate方法
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    // 获得焦点时高亮
    [self setValue:LSLPlaceholderFocusColor forKeyPath:LSLPlaceholderColorKey];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    // 失去焦点时变灰色
    [self setValue:LSLPlaceholderDefaultColor forKeyPath:LSLPlaceholderColorKey];
}
  • 方法2,分别给文本框编辑开始和结束时绑定事件
@implementation LSLLoginRegisterTextFiled
- (void)awakeFromNib
{
    // 方法2,分别给文本框编辑开始和结束时绑定事件
    [self addTarget:self action:@selector(beginEditing) forControlEvents:UIControlEventEditingDidBegin];
    [self addTarget:self action:@selector(endEditing) forControlEvents:UIControlEventEditingDidEnd];
}

#pragma mark - 方法2,文本框编辑开始和结束时对应的事件
- (void)beginEditing
{
    // 获得焦点时高亮
    [self setValue:LSLPlaceholderFocusColor forKeyPath:LSLPlaceholderColorKey];
}

- (void)endEditing
{
    // 失去焦点时变灰色
    [self setValue:LSLPlaceholderDefaultColor forKeyPath:LSLPlaceholderColorKey];
}
@end
  • 方法3,通过通知,监听文本框编辑开始和结束
@implementation LSLLoginRegisterTextFiled
- (void)awakeFromNib
{
    // 方法3,通过通知,监听文本框编辑开始和结束
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginEditing) name:UITextFieldTextDidBeginEditingNotification object:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEditing) name:UITextFieldTextDidEndEditingNotification object:self];
}

#pragma mark - 方法3,文本框编辑开始和结束时对应的事件
- (void)beginEditing
{
    // 获得焦点时高亮
    [self setValue:LSLPlaceholderFocusColor forKeyPath:LSLPlaceholderColorKey];
}

- (void)endEditing
{
    // 失去焦点时变灰色
    [self setValue:LSLPlaceholderDefaultColor forKeyPath:LSLPlaceholderColorKey];
}

#pragma mark - 一定要在对象销毁之前移除监听
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
  • 方法4,重写文本框获得焦点时的becomeFirstResponder方法和失去焦点时的resignFirstResponder方法
@implementation LSLLoginRegisterTextFiled
#pragma mark - 方法4,重写文本框获得焦点时和失去焦点时的方法
- (BOOL)becomeFirstResponder
{
    // 获得焦点时高亮
    [self setValue:LSLPlaceholderFocusColor forKeyPath:LSLPlaceholderColorKey];
    return [super becomeFirstResponder];
}

- (BOOL)resignFirstResponder
{
    // 失去焦点时变灰色
    [self setValue:LSLPlaceholderDefaultColor forKeyPath:LSLPlaceholderColorKey];
    return [super resignFirstResponder];
}
@end