iOS:根据键盘的弹出隐藏自动调整View的位置

原创:http://www.cnphp6.com/archives/67220

首先需要监听键盘通知,这里我们监听UIKeyboardWillChangeFrameNotification,只要键盘位置改变了(不管是弹出还是隐藏),系统都会发出该通知.  
其次调整View(被键盘弹出隐藏的控件)的高度.(这里我们就需要知道通知的内容,因为通知中包含了键盘弹出和隐藏的所有信息).  
//—-打印出来通知的userInfo信息——  
/*UIKeyboardAnimationCurveUserInfoKey = 7;  
UIKeyboardAnimationDurationUserInfoKey = “0.25”;  
UIKeyboardBou… 

1.首先注册系统通知

    //监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];

2.键盘将要改变时的相应处理

-(void)keyboardWillChangeFrameNotification:(NSNotification *)note{
  
    //取出键盘动画的时间(根据userInfo的key----UIKeyboardAnimationDurationUserInfoKey)
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    //取得键盘最后的frame(根据userInfo的key----UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";)
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    //计算控制器的view需要平移的距离
    CGFloat transformY = keyboardFrame.origin.y - self.view.frame.size.height;
    
    //执行动画
    [UIView animateWithDuration:duration animations:^{
        //平移
        self.view.transform = CGAffineTransformMakeTranslation(0, transformY);
    }];
}

3.这样其实还没完(存在内存隐患)还需要重写dealloc方法

-(  void )dealloc{ 

//  使用通知中心后必须重写 dealloc  方法 ,  进行释放 (ARC)(  非 ARC  还需要写上[super dealloc];) 

//removeObserver和 addObserver相对应.

[[ NSNotificationCenter defaultCenter  ] removeObserver  : self ];

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值