在使用UITextFIeld控件时,键盘的出现通常会挡住部分视图,所以需要在键盘出现时移动视图位置,键盘落下后视图回到原来位置,看看代码实现
#import "ViewController.h"
@implementation ViewController
{
UITextField * tf; //文本框
CGRect originFrame;//文本框初始尺寸
}
- (void)viewDidLoad {
[super viewDidLoad];
//主要思路:
//1.监听键盘弹出和落下
//2.键盘弹出:获取键盘高度,把文本框向上移
//3.键盘落下:文本框回到初始位置
//屏幕尺寸
CGFloat kWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat kHeight = [UIScreen mainScreen].bounds.size.height;
self.view.backgroundColor = [UIColor whiteColor];
//创建文本输入框
tf = [[UITextField alloc] initWithFrame:CGRectMake(50, kHeight-80,kWidth-100, 50)];
tf.borderStyle = UITextBorderStyleLine;
tf.placeholder = @"请输入内容";
[self.view addSubview:tf];
//保存文本框初始位置
originFrame = tf.frame;
//把当前控制器注册为监听者,监听键盘的弹出和隐藏
//UIKeyboardDidShowNotification 键盘弹出
//UIKeyboardDidHideNotification 键盘隐藏
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHide:) name:UIKeyboardDidHideNotification object:nil];
}
//点击屏幕,文本框释放第一响应者身份,让键盘落下
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[tf resignFirstResponder];
}
//键盘弹出,文本框移动到键盘上方
- (void)keyBoardShow:(NSNotification *)notification{
//获取通知中的信息,其它信息贴在下面
NSDictionary * info = [notification userInfo];
NSLog(@"%@", info);
//获取键盘尺寸
CGSize keySize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//文本框现在的位置
CGRect rect = CGRectMake(originFrame.origin.x, originFrame.origin.y-keySize.height, originFrame.size.width, originFrame.size.height);
//使用动画移动文本框
[UIView animateWithDuration:0.2 animations:^{
tf.frame = rect;
}];
// [notification userInfo]内容
// UIKeyboardAnimationCurveUserInfoKey = 7; //键盘动画轨迹类型
// UIKeyboardAnimationDurationUserInfoKey = "0.25"; //键盘弹出动画时长
// UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}"; //键盘bounds
// UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}"; //键盘刚要弹出时center
// UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}"; //键盘弹出后center
// UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}"; //键盘刚要弹出时frame
// UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}"; //键盘弹出后frame
// UIKeyboardIsLocalUserInfoKey = 1; //是否是本地键盘
}
//键盘隐藏,文本框回到原来位置
- (void)keyBoardHide:(NSNotification *)info{
[UIView animateWithDuration:0.2 animations:^{
tf.frame = originFrame;
}];
}
- (void)dealloc{
//取消监听
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end