一、案例介绍:利用UIScrollView, 避免键盘遮挡控件;图01、图02其实是存在第三个UIButton的,滑动屏幕可以看到,如图06。效果如图01,图02。
图01图02图03图06
二、案例步骤:
1、选择Single View Application新建项目,取名cq.30.ScrollView,如图03。
2、Main.storyboard如图04,图05。
图04图05
3、CQ30ViewController.h
#import <UIKit/UIKit.h> @interface CQ30ViewController : UIViewController<UITextFieldDelegate> { BOOL keyboardVisible; //键盘出现标识 } @property (weak, nonatomic) IBOutlet UIScrollView *scrollView; @property (weak, nonatomic) IBOutlet UITextField *textField; @end
4、CQ30ViewController.m
》通过UITextFieldDelegate实现对UITextField放弃第一响应者身份,关闭键盘
#pragma mark -- UITextFieldDelegate method - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; }
》注册监听键盘打开与关闭通知
-(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]; }
》通过监听键盘的打开与关闭动态改变UIScrollView的frame,聚焦当前UITextField。
-(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; }