一开始 做项目的时候 忽略了 UITextfield 和键盘 高度的事, 走了不少弯路 废话不说 直接直接上代码 东西真心不难
//
// CLoudFitTextField.h
// CloudFITC
//
// Created by 卜成哲 on 16/8/12.
// Copyright © 2016年 王景欣. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface CLoudFitTextField : UITextField
@end
//
// CLoudFitTextField.m
// CloudFITC
//
// Created by 卜成哲 on 16/8/12.
// Copyright © 2016年 王景欣. All rights reserved.
//
#import "CLoudFitTextField.h"
#import "AppDelegate.h"
// 屏幕宽高值
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
@implementation CLoudFitTextField
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
//注册通知获取键盘高度
//增加监听,当键盘出现或改变时收出消息
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
//增加监听,当键退出时收出消息
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
return self;
}
- (void)keyboardWillShow:(NSNotification *)aNotification
{
//获取键盘的高度
NSDictionary *userInfo = [aNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
//相对坐标 基于window
CGRect rect = [self convertRect:self.bounds toView:self.window];
//只有控件在键盘下面 才变位置
if (CGRectGetMaxY(rect) > (kScreenHeight - keyboardRect.size.height)) {
self.window.frame = CGRectMake(0, - (keyboardRect.size.height - (kScreenHeight - rect.origin.y) + self.frame.size.height), kScreenWidth, kScreenHeight);
}
}
//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
self.window.frame = [UIScreen mainScreen].bounds;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
@end
思路就是 获取键盘的高度 和 控件的 绝对坐标(其实也不是绝对坐标, 就是相对于Window) 判断控件是不是被键盘覆盖到, 如果覆盖到了 改变Window 的位置