美文网首页开发文档iOS 开发 iOS Developer
iOS textField键盘弹出/收起 自动上下移

iOS textField键盘弹出/收起 自动上下移

作者: gainna | 来源:发表于2016-01-28 18:14 被阅读1846次

    在做聊天或某些特定界面的时候,需要触发textField的键盘。而部分界面会被遮挡住。本文提供了一个很好的解决方法。

    - (void)viewDidLoad {
    
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didClickKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(didKboardDisappear:) name:UIKeyboardWillHideNotification object:nil];
    
    }
    
    #pragma mark -      键盘即将跳出
    
    -(void)didClickKeyboard:(NSNotification *)sender{
    
    CGFloat durition = [sender.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
    
    CGRect keyboardRect = [sender.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    
    CGFloat keyboardHeight = keyboardRect.size.height;
    
    [UIView animateWithDuration:durition animations:^{
    
    self.view.transform = CGAffineTransformMakeTranslation(0, -keyboardHeight);
    
    }];
    
    }
    
    #pragma mark -      当键盘即将消失
    
    -(void)didKboardDisappear:(NSNotification *)sender{
    
    CGFloat duration = [sender.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
    
    self.view.transform = CGAffineTransformIdentity;
    
    }];
    
    }
    

    其中打印一下观察者的userInfo 属性可以获取到:

    UIKeyboardAnimationCurveUserInfoKey = 7;

    UIKeyboardAnimationDurationUserInfoKey = "0.25";

    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 253}}";

    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 353.5}";

    UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 606.5}";

    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";

    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 480}, {320, 253}}";

    UIKeyboardIsLocalUserInfoKey = 1;

    添加上键盘消失的代码,测试一下。希望对大家有用。

    相关文章

      网友评论

      • 朋友有朋:写的真心不赖,请加QQ437913028,愿意跟随你,学习!!!!!
      • 95114676ad51:方法不错,不过很有局限性。
        gainna:@祖师爷 昂 新手 求指导

      本文标题:iOS textField键盘弹出/收起 自动上下移

      本文链接:https://www.haomeiwen.com/subject/ddrjkttx.html