新建一个SingleViewApplication应用, 在storyboard中拖一个scrollView充满视图,拖三个Button,一个textField,如图:
其中第三个Button,设置其位置,使其超出视图范围,如图:
为scrollView,textField设置输出口,为textField设置代理,并且定义键盘状态的变量:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextFieldDelegate> {
BOOL keyboardVisible;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end
scrollView的大小;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.textField.delegate = self;
self.scrollView.contentSize = CGSizeMake(320, 650);
}
设置
scrollView偏移位置
-(void)viewDidAppear:(BOOL)animated{
[self.scrollView setContentOffset:CGPointMake(0, 110) animated:YES];
[super viewDidAppear:YES];
}
设置键盘出现后的布局
-(void) keyboardDidShow: (NSNotification *)notif {
if (keyboardVisible) {//键盘已经出现要忽略通知
return;
}
// 获得键盘尺寸
NSDictionary* info = [notif userInfo];
NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
//重新定义ScrollView的尺寸
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height -= (keyboardSize.height);
self.scrollView.frame = viewFrame;
//滚动到当前文本框
CGRect textFieldRect = [self.textField frame];
[self.scrollView scrollRectToVisible:textFieldRect animated:YES];
keyboardVisible = YES;
}
-(void) keyboardDidHide: (NSNotification *)notif {
NSDictionary* info = [notif userInfo];
NSValue* aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
CGRect viewFrame = self.scrollView.frame;
viewFrame.size.height += keyboardSize.height;
self.scrollView.frame = viewFrame;
if (!keyboardVisible) {
return;
}
keyboardVisible = NO;
}
注册键盘打开关闭通知:
-(void) viewWillAppear:(BOOL)animated {
//注册键盘出现通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidShow:)
name: UIKeyboardDidShowNotification object:nil];
//注册键盘隐藏通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardDidHide:)
name: UIKeyboardDidHideNotification object:nil];
[super viewWillAppear:animated];
}
-(void) viewWillDisappear:(BOOL)animated {
//解除键盘出现通知
[[NSNotificationCenter defaultCenter] removeObserver:self
name: UIKeyboardDidShowNotification object:nil];
//解除键盘隐藏通知
[[NSNotificationCenter defaultCenter] removeObserver:self
name: UIKeyboardDidHideNotification object:nil];
[super viewWillDisappear:animated];
}
最后取消键盘响应:
#pragma mark -- UITextFieldDelegate method
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
最终实现键盘出现时候,不会遮盖视图;并且出现键盘后按return键,键盘消失。