首页 > 代码库 > iOS.UIKit.05.UIScrollView
iOS.UIKit.05.UIScrollView
一、案例介绍:利用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 =http://www.mamicode.com/ [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 =http://www.mamicode.com/ [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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。