zoukankan      html  css  js  c++  java
  • iOS 关于退出键盘两种方法和避免遮挡

    退出键盘

       方法1:不使用代理,直接使用;

     -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

    {

        [self.textField resignFirstResponder];

    }

          方法2:使用代理,通过点击键盘Return键收起键盘

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

        //textField放弃第一响应者 (收起键盘)

        [textField resignFirstResponder];

        return YES;

    }

    两种方法可以同时添加,还有几种方法:

    这三种方法在调用时,也都可以退出键盘。

    [self.view endEditing:YES];
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];


    避免键盘弹出遮挡输入框:

    方法1:自己代码集成。

    在viewDidLoad中注册两个通知,监听键盘弹出和退出

     //增加监听,当键盘出现或改变时收出消息 //增加监听,当键退出时收出消息
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; 

    //增加监听,当键退出时收出消息
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

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

        NSDictionary *info = [aNotification userInfo];

        CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

        //目标视图UITextField

        CGRect frame = self.textField.frame;

        int offsetY = frame.origin.y + frame.size.height - (self.view.frame.size.height - keyboardSize.height);

        NSTimeInterval animationDuration = 0.30f;

        [UIView beginAnimations:@"ResizeView" context:nil];

        [UIView setAnimationDuration:animationDuration];

        if(offsetY > 0)

        {

            self.view.frame = CGRectMake(0, -offsetY, self.view.frame.size.width, self.view.frame.size.height);

        }

        [UIView commitAnimations];    

    }

    //键盘隐藏后将视图恢复到原始状态

    -(void)keyboardWillHide:(NSNotification *)aNotification

    {

        NSTimeInterval animationDuration = 0.30f;

        [UIView beginAnimations:@"ResizeView" context:nil];

        [UIView setAnimationDuration:animationDuration];

        self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

        [UIView commitAnimations];

    }

    方法2:使用IQKeyboardManager:

       github地址: https://github.com/hackiftekhar/IQKeyboardManager






  • 相关阅读:
    postgres column reference "id" is ambiguous
    网络 内网穿透frp
    odoo12 支付宝在线支付
    odoo 账号登录不上,重置密码也不管用
    odoo 取消保存提示
    聊聊redis分布式锁的8大坑 转载
    用 Keepalived+HAProxy 实现高可用负载均衡的配置方法 转载
    Nginx+keepalived 实现高可用,常用防盗链及动静分离配置 转载
    Git 实用技巧记录 转载:https://mp.weixin.qq.com/s/o6FvGfiG9b57xTeXlBzzQQ
    5 个冷门但非常实用的 Kubectl 使用技巧,99% 的人都不知道 https://mp.weixin.qq.com/s/h4_KRmsVSnlqCmIJh0altA
  • 原文地址:https://www.cnblogs.com/xu1peng/p/8252262.html
Copyright © 2011-2022 走看看