ios键盘的第一响应者和打开关闭触发的通知

键盘的打开、关闭(放弃第一响应者)

TextField、TextView这些控件处于编辑状态时,它们就会成为“第一响应者”,不同的控件成为“第一响应者”的表现各不相同,文本框这类的就是系统会自动弹出键盘,不需要做任何操作,但关闭键盘就要相反的,代码控制让控件放弃“第一响应者”的身份。
调用UIResponder类中的resignFirstResponder方法,此方法一般在点击背景视图或者是按键盘上的return后出发。

这边用单击return键关闭键盘: 利用控件的委托协议实现。   
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

    if([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

打开或关闭键盘触发的系统通知

//注册键盘出现通知;
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardDidShow:)name:UIKeyboardDidShowNotificationobject:nil];
//注册键盘消失通知;
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyboardDidHide:)name:UIKeyboardDidHideNotificationobject:nil];

键盘出现和消失时候方法实现

-(void)keyboardDidShow:(NSNotification *)notification
{
    //键盘打开;
}
-(void)keyboardDidHide:(NSNotification *)notification
{
    //键盘关闭
}

视图将要消失的时候删除键盘通知;

-(void)viewWillDisappear:(BOOL)animated
{
    //解除键出现盘通知;
    [[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardDidShowNotificationobject:nil];
    //解除键盘隐藏通知;
    [[NSNotificationCenterdefaultCenter]removeObserver:selfname:UIKeyboardDidHideNotificationobject:nil];
}

键盘的类型

具体参照此文章
设定Keyboard Type 即可,同时Return Key指定的是return键的文本内容。

猜你喜欢

转载自blog.csdn.net/qq_14902389/article/details/52518219
今日推荐