【iOS开发】跟踪键盘的移动

1.当向一个输入框输入文字时,虚拟键盘可能会弹起覆盖掉输入框。为了解决这个问题,我们需要让输入框跟随键盘一起移动。当键盘有活动时,会发送一条对应的通知。

    UIKeyboardWillShowNotification
    UIKeyboardDidShowNotification
    UIKeyboardWillHideNotification
    UIKeyboardDidHideNotification

利用此通知,我们可以改变输入框的位置,避免输入框被键盘所覆盖掉。
通知UIKeyboardWillShowNotification包含的消息如下:

{name = UIKeyboardWillChangeFrameNotification; userInfo = {
    UIKeyboardAnimationCurveUserInfoKey = 7;
    UIKeyboardAnimationDurationUserInfoKey = "0.25";
    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {320, 253}}";
    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {160, 606.5}";
    UIKeyboardCenterEndUserInfoKey = "NSPoint: {160, 353.5}";
    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 480}, {320, 253}}";
    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";
}}

由此我们可以获取键盘弹出时的各种属性,然后重新设置输入框的位置

CGFloat time = [notification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue];
    [UIView animateWithDuration:time animations:^{
        CGRect rect = [notification.userInfo[@"UIKeyboardBoundsUserInfoKey"] CGRectValue];

        self.chatView.transform = CGAffineTransformMakeTranslation(0, -rect.size.height);
    }];

2.当点击return按键,希望键盘消失。有以下几种解决方案

(1)当输入框为textField时,我们可以利用它的代理方法

 - (BOOL)textFieldShouldReturn:(UITextField *)textField {

 [textField resignFirstResponder];

 return YES;

}

监听return按键的点击,然后让输入框丢失第一响应,键盘消失

(2)当输入框为textView时,我们可以利用代理方法

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

        if ([text isEqualToString:@"\n"]) {  

            [textView resignFirstResponder];  
            return NO;  
        }  

        return YES;  
    }  

当点击return时候,丢失第一响应。
备注:我们还可以利用此代理方法,限制输入文字的字数,textfield也有类似方法

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text  
{  
    if (range.location>=100)   
    {  
        return  NO;  
    }  
    else   
    {  
        return YES;  
    }  
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值