//
// LPViewController.m
// demo
//
// Created by linpeng on 14-7-21.
// Copyright (c) 2014年 linpeng. All rights reserved.
//
#import "LPViewController.h"
@interface LPViewController ()
{
UITextField *txt,*txt2;
}
@property(nonatomic,strong)UITextField *txt,*txt2;
@end
@implementation LPViewController
@synthesize txt = txt;
@synthesize txt2 = txt2;
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:1]];
txt = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 40)];
txt.layer.borderColor = [UIColor blackColor].CGColor;
txt.layer.borderWidth = 1;
[self.view addSubview:txt];
UITextField *txt1 = [[UITextField alloc] initWithFrame:CGRectMake(100, 230, 100, 40)];
txt1.layer.borderColor = [UIColor blackColor].CGColor;
txt1.layer.borderWidth = 1;
[self.view addSubview:txt1];
txt2 = [[UITextField alloc] initWithFrame:CGRectMake(100, 400, 100, 40)];
txt2.layer.borderColor = [UIColor blackColor].CGColor;
txt2.layer.borderWidth = 1;
[self.view addSubview:txt2];
//键盘变化结束后: UIKeyboardWillChangeFrameNotification
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangedFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
/**
* 视图的第一响应者
*
* @return 响应者视图
*/
-(UIView *)firstResponse
{
if ([self.view isFirstResponder]) {
return self.view;
}else
{
for (UIView *view in [self.view subviews]) {
if ([view isFirstResponder]&&view!=nil) {
return view;
}
}
return nil;
}
}
/**
* 键盘变化监听
*
* @param noti 键盘变化通知
*/
-(void)keyboardWillChangedFrame:(NSNotification *)noti{
//UIKeyboardFrameEndUserInfoKey 键盘变化结束后的frame
CGRect endFrame = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
float maxY = CGRectGetMaxY(endFrame);//orign.y + size.height
float keboardHeiht = endFrame.size.height;//键盘高度
UIView *view = [self firstResponse];//视图的响应者
CGFloat point = 0;
//控件底部(y+h)+键盘高度>屏幕高度===》会遮挡
if ((view.frame.origin.y+keboardHeiht+view.frame.size.height)>[UIScreen mainScreen].bounds.size.height) {
//if (view.frame.origin.y>keboardHeiht) {
point = view.frame.origin.y-keboardHeiht;//移动距离保证不会挡住
}
if (maxY == [UIScreen mainScreen].bounds.size.height) {
[UIView animateWithDuration:0.3 animations:^{
[self.view setFrame:CGRectMake(self.view.frame.origin.x, -point, self.view.frame.size.width, self.view.frame.size.height)];//可以选择性的移动需要移动的视图 这里选择self.view
}];
} else {
[UIView animateWithDuration:0.3 animations:^{
[self.view setFrame:CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height)];
}];
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[[self firstResponse] resignFirstResponder];
// [txt2 resignFirstResponder];
// [txt resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
iOS 键盘遮挡问题(详细)
最新推荐文章于 2024-05-09 09:50:03 发布