• 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






  • 相关阅读:
    基于I2C总线的MPU6050学习笔记
    基于I2C总线的0.96寸OLED显示屏驱动
    I2C总线协议的软件模拟实现方法
    I2C总线通讯协议
    Exynos4412从SD卡启动的简单网络文件系统制作
    多版本 PHP 环境下,使用指定版本运行composer
    腾讯云服务器 lnmp 开启 MySQL 远程访问权限
    MySQL添加新用户和新增权限
    Laravel 框架创建软链接
    Git 保存登录凭证
  • 原文地址:https://www.cnblogs.com/xu1peng/p/8252262.html
Copyright © 2020-2023  润新知