UITextField 事件监听四种方式

一、添加监听对象

-(void)awakeFromNib{
    [super awakeFromNib];
    [self addTarget:self action:@selector(textFildBegin) forControlEvents:UIControlEventEditingDidBegin];
    [self addTarget:self action:@selector(textFildEnd) forControlEvents:UIControlEventEditingDidEnd];
    
    
    
}
-(void)textFildBegin{
    NSLog(@"begin");

}

-(void)textFildEnd{
    NSLog(@"end");
}


二、代理

@interface ViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet XMGLoginTextField *phoneNumber;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.phoneNumber.delegate = self;
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -UITextFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    NSLog(@"begin");
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    NSLog(@"end");
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self.view endEditing:YES];
}

三、通知

- (void)awakeFromNib
{
    // 设置光标颜色
    self.tintColor = [UIColor whiteColor];
    // 设置默认的占位文字颜色
    [self setValue:[UIColor grayColor] forKeyPath:XMGPlaceholderColorKey];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(beginEditing) name:UITextFieldTextDidBeginEditingNotification object:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEditing) name:UITextFieldTextDidEndEditingNotification object:self];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)beginEditing
{
    [self setValue:[UIColor whiteColor] forKeyPath:XMGPlaceholderColorKey];
}

- (void)endEditing
{
    [self setValue:[UIColor grayColor] forKeyPath:XMGPlaceholderColorKey];
}
@end

四、是否是键盘的第一响应用者

//键盘出现
-(BOOL)becomeFirstResponder{
        self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    return [super becomeFirstResponder];
}

//键盘退出
-(BOOL)resignFirstResponder{
    self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:@{NSForegroundColorAttributeName:[UIColor darkGrayColor]}];
    return [super resignFirstResponder];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,637评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,259评论 4 61
  • 你,是我心空的一颗星辰 闪闪烁烁,飘飘忽忽 我,多想把你定格在眼前 夜夜年年,永永远远 夜晚是时间的伤痕 悄然划满...
    陈笃阅读 196评论 0 2
  • 只一眼便赔上了一生……
    九月天蝎阅读 329评论 0 0
  • 第081讲 米奇老鼠的阴谋诡计 年金的概念 持续多期的收入称为“年金”。 今年我赚一块钱,明天我赚一块钱,后年我赚...
    势从千里奔阅读 1,582评论 0 0