iOS开发-键盘通知

来源:互联网 发布:护眼仪有用吗 知乎 编辑:程序博客网 时间:2024/05/22 02:21

iOS开发-键盘通知

4种常用通知

UIKeyboardWillShowNotification、UIKeyboardDidShowNotification、UIKeyboardDidHideNotification、UIKeyboardDidHideNotification

注册与解除

addObserver与removeObserver需要在对应的生命周期中成对出现。即有“添加”有“删除”。

- (void)viewWillAppear:(BOOL)animated{    [super viewWillAppear:animated];    // 注册键盘通知    // 即将显示    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];    // 显示    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidShowNotification:) name:UIKeyboardDidShowNotification object:nil];    // 即将隐藏    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideNotification:) name:UIKeyboardDidHideNotification object:nil];    // 隐藏    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHideNotification:) name:UIKeyboardDidHideNotification object:nil];}- (void)viewWillDisappear:(BOOL)animated{    [super viewWillDisappear:animated];    // 接触键盘通知    // 即将显示    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];    // 显示    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];    // 即将隐藏    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];    // 隐藏    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];}- (void) keyboardWillShowNotification: (NSNotification *)notif{    NSLog(@"键盘即将显示");}- (void) keyboardDidShowNotification: (NSNotification *)notif{    NSLog(@"键盘显示");}- (void) keyboardWillHideNotification:(NSNotification *)notif{    NSLog(@"键盘即将隐藏");}- (void) keyboardDidHideNotification:(NSNotification *)notif{    NSLog(@"键盘隐藏");}
1 0