iOS输入框被键盘挡住的解决方法

iOS开发中,经常会遇到输入框被键盘挡住的情况,通过查阅资料和自己的思考,想出来下面这个方法:
基本思路:

  1. 在点击UITextField时,会自动调用 textFieldShouldBeginEditing 方法,在该方法中获取光标高度;
  2. 利用通知中心监听 UIKeyboardWillShowNotification ,在监听方法中可以获取到键盘高度,将键盘高度与光标高度相比较:如果键盘高度大于光标高度,则调整self.view的frame,使UITextField可以显示出来,将差值保存下来;如果小于,不做操作.
  3. 利用通知中心监听 name:UIKeyboardWillHideNotification ,在监听方法中判断差值是否大于0:如果大于,说明已经调整过self.view的frame,现在需要调整回来;如果小于,不做操作.

这就是实现的基本思路,在此基础上,就可以现在了.基础比较好的可以自己去研究了.如果嫌麻烦,可以接着看.我接着写具体实现过程.
我做了一个Demo,其中包含3个UITextField,自上而下:tfAccount,tfPassword,tfEmail.
第一步: 实现代理

  1. 实现代理: _tfPassword.delegate = self;
  2. 遵守协议: UITextFieldDelegate
  3. 实现方法: - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{}

第二步: 获取点击的UITextField距底部的高度

#pragma mark- UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([textField isEqual:self.tfAccount]) {
        _cursorHeight = self.view.frame.size.height - CGRectGetMaxY(textField.frame);
    }else if ([textField isEqual:self.tfPassword]) {
        _cursorHeight = self.view.frame.size.height - CGRectGetMaxY(textField.frame);
    }else if ([textField isEqual:self.tfEmail]) {
        _cursorHeight = self.view.frame.size.height - CGRectGetMaxY(textField.frame);
    }
    return YES;
}

其中,在类的延展中声明_cursorHeight: float _cursorHeight; 这是光标距底部的高度.

第三步:通知,监听

- (void)viewDidLoad {
    [super 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 *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    float keyboardHeight = keyboardRect.size.height;
    _spacingWithKeyboardAndCursor = keyboardHeight - _cursorHeight;
    if (_spacingWithKeyboardAndCursor > 0) {
        [UIView animateWithDuration:kAnimationDuration animations:^{
            //将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
            self.view.frame = CGRectMake(0.0f, -(_spacingWithKeyboardAndCursor + 5.0f), self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}
//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification {
    if (_spacingWithKeyboardAndCursor > 0) {
        [UIView animateWithDuration:kAnimationDuration animations:^{
            //将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
            self.view.frame = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

其中,在类的延展中声明_spacingWithKeyboardAndCursor: float _spacingWithKeyboardAndCursor; 这是光标与键盘之间的间隔.

至此,一个最简单的Demo完成了.为了便于理解,除了必要的代码,其他任何有利于完善的代码都没有添加.

呈上代码:
(注:这是ViewController.m中的代码,其他页面没有添加任何代码,大家可以直接新建一个项目,将代码拷过去,进行测试)

//
//  ViewController.m
//  ChangeKeyboardHeightDemo
//
//  Created by Suzhenyu on 16/3/16.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "ViewController.h"

static const CGFloat kSpacing = 8.0f;                       //间隔
static const NSTimeInterval kAnimationDuration = 1.0f;      //动画时间

@interface ViewController ()
{
    float _cursorHeight;                                    //光标距底部的高度
    float _spacingWithKeyboardAndCursor;                    //光标与键盘之间的间隔
}

@property (nonatomic, strong) UITextField *tfAccount;
@property (nonatomic, strong) UITextField *tfPassword;
@property (nonatomic, strong) UITextField *tfEmail;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor darkGrayColor];

    [self.view addSubview:self.tfAccount];
    [self.view addSubview:self.tfPassword];
    [self.view addSubview:self.tfEmail];

    //增加监听,当键盘出现或改变时收出消息
    [[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 *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    float keyboardHeight = keyboardRect.size.height;
    _spacingWithKeyboardAndCursor = keyboardHeight - _cursorHeight;
    if (_spacingWithKeyboardAndCursor > 0) {
        [UIView animateWithDuration:kAnimationDuration animations:^{
            //将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
            self.view.frame = CGRectMake(0.0f, -(_spacingWithKeyboardAndCursor), self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}
//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification {
    if (_spacingWithKeyboardAndCursor > 0) {
        [UIView animateWithDuration:kAnimationDuration animations:^{
            //将视图的Y坐标向上移动offset个单位,以使下面腾出地方用于软键盘的显示
            self.view.frame = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
}

#pragma mark- 懒加载
-(UITextField *)tfAccount {
    if (!_tfAccount) {
        _tfAccount = [[UITextField alloc] initWithFrame:CGRectMake(kSpacing, self.view.frame.size.height - 180, self.view.frame.size.width - kSpacing * 2.0, 30)];
        _tfAccount.backgroundColor = [UIColor whiteColor];
        _tfAccount.placeholder = @"请输入账号";
        _tfAccount.delegate = self;
    }

    return _tfAccount;
}

-(UITextField *)tfPassword {
    if (!_tfPassword) {
        _tfPassword = [[UITextField alloc] initWithFrame:CGRectMake(kSpacing, self.view.frame.size.height - 120, self.view.frame.size.width - kSpacing * 2.0, 30)];
        _tfPassword.backgroundColor = [UIColor whiteColor];
        _tfPassword.placeholder = @"请输入密码";
        _tfPassword.delegate = self;
    }

    return _tfPassword;
}

-(UITextField *)tfEmail {
    if (!_tfEmail) {
        _tfEmail = [[UITextField alloc] initWithFrame:CGRectMake(kSpacing, self.view.frame.size.height - 60, self.view.frame.size.width - kSpacing * 2.0, 30)];
        _tfEmail.backgroundColor = [UIColor whiteColor];
        _tfEmail.placeholder = @"请输入邮箱";
        _tfEmail.delegate = self;
    }

    return _tfEmail;
}

#pragma mark- UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([textField isEqual:self.tfAccount]) {
        _cursorHeight = self.view.frame.size.height - CGRectGetMaxY(textField.frame);
    }else if ([textField isEqual:self.tfPassword]) {
        _cursorHeight = self.view.frame.size.height - CGRectGetMaxY(textField.frame);
    }else if ([textField isEqual:self.tfEmail]) {
        _cursorHeight = self.view.frame.size.height - CGRectGetMaxY(textField.frame);
    }

    return YES;
}


@end

你可能感兴趣的:(iOS输入框被键盘挡住的解决方法)