IOS 键盘使用

在点击录入框时键盘会自动升起,这是系统自动操作,但很多时候键盘会把视图中控件挡住,这样我们就得对键盘升做一些操作,

首先,要监听键盘升起事件,系统在升起键盘时会发出UIKeyboardWillShowNotification信号,要捕捉它并设置处理函数。

[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

keyboardWillShow是处理函数,在函数做视图位置上升变化。键盘处理函数中改变视图位置要注意个问题,如果键盘弹出不是英文键盘,会收到多次信号,这是因为系统在切换键盘时都会发出keyboardWillShow信号。比如现在使用的是中文输入法,系统首先弹出键盘是英文键盘会发出信号,然后在切换到中文键盘又会发出信号,


还要监听键盘降下事件,在键盘落下时把视图位置反回原处,键盘落下系统发出UIKeyboardWillHideNotification信号

[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];


键盘处理函数

-(void) keyboardWillShow:(NSNotification *)note{

   // 取得键盘位置高度

   CGRect keyboardBounds;

    [[note.userInfovalueForKey:UIKeyboardFrameEndUserInfoKey]getValue: &keyboardBounds];

    NSNumber *duration = [note.userInfoobjectForKey:UIKeyboardAnimationDurationUserInfoKey];

    NSNumber *curve = [note.userInfoobjectForKey:UIKeyboardAnimationCurveUserInfoKey];

    

    // Need to translate the bounds to account for rotation.

    keyboardBounds = [self.viewconvertRect:keyboardBounds toView:nil];

    

    //改变视图位置

   CGRect containerFrame = containerView.frame;

    containerFrame.origin.y =self.view.bounds.size.height - keyboardBounds.size.height;

    // animations settings

    [UIViewbeginAnimations:nilcontext:NULL];

    [UIViewsetAnimationBeginsFromCurrentState:YES];

    [UIViewsetAnimationDuration:[duration doubleValue]];

    [UIViewsetAnimationCurve:[curve intValue]];

    

    // set views with new info

   containerView.frame = containerFrame;

    

    

    // commit animations

    [UIViewcommitAnimations];

}


-(void) keyboardWillHide:(NSNotification *)note{

    NSNumber *duration = [note.userInfoobjectForKey:UIKeyboardAnimationDurationUserInfoKey];

    NSNumber *curve = [note.userInfoobjectForKey:UIKeyboardAnimationCurveUserInfoKey];

    

    // get a rect for the textView frame

   CGRect containerFrame = containerView.frame;

    containerFrame.origin.y =self.view.bounds.size.height - containerFrame.size.height + 20;

    

    // animations settings

    [UIViewbeginAnimations:nilcontext:NULL];

    [UIViewsetAnimationBeginsFromCurrentState:YES];

    [UIViewsetAnimationDuration:[duration doubleValue]];

    [UIViewsetAnimationCurve:[curve intValue]];

    

    // set views with new info

   containerView.frame = containerFrame;

    // commit animations

    [UIViewcommitAnimations];

}


也可以监听某些按件,让某个控件关闭键盘

-(IBAction)sendMessage_Click:(id)sender

{

    [textViewresignFirstResponder];

}





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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值