【代码笔记】iOS-键盘自适应弹出
2017-06-30 09:19
267 查看
一,效果图。
二,工程图。
三,代码。
ViewController.h
ViewController.m
二,工程图。
三,代码。
ViewController.h
#import <UIKit/UIKit.h> @interface ViewController : UIViewController <UITextFieldDelegate> @end
ViewController.m
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UITextField *field=[[UITextField alloc]initWithFrame:CGRectMake(100, 300, 50, 50)]; field.backgroundColor=[UIColor redColor]; field.delegate=self; [self.view addSubview:field]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; } #pragma -mark -keyboard notificatin - (void)keyboardWillShow:(NSNotification *)notification { NSDictionary *info = [notification userInfo]; // keyboardHeight 为键盘高度 CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size; [self animateViewWithKeyboardHeight:keyboardSize.height]; } - (void)keyboardWillHide:(NSNotification *)notification { [self animateViewWithKeyboardHeight:0.0]; } - (void)animateViewWithKeyboardHeight:(CGFloat)keyboardHeight { NSTimeInterval animationDuration = 0.3f; CGFloat height = self.view.bounds.size.height; CGFloat width = self.view.bounds.size.width; CGFloat topSize = 0.0; CGFloat viewH = self.view.frame.size.height-64; CGFloat deviceHeight = [UIScreen mainScreen].bounds.size.height; CGFloat animateH = deviceHeight - viewH - keyboardHeight; if (animateH >= 0) { topSize = 0; CGRect toRect = CGRectMake(0, topSize, width, height); self.view.frame = toRect; } else { topSize = animateH; CGRect toRect = CGRectMake(0, topSize, width, height); [UIView animateWithDuration:animationDuration animations:^{ self.view.frame = toRect; }]; } } #pragma -mark -UITextFieldDelegate -(BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
相关文章推荐
- 【代码笔记】iOS-键盘自适应弹出
- 【代码笔记】iOS-轮询弹出框
- iOS开发笔记(1) -- 利用弹出键盘时使视图跟随键盘上移
- 【代码笔记】iOS-UILable高度自适应(sizeWithFont)
- 【代码笔记】iOS-自定义弹出框
- 【代码笔记】iOS-只让textField使用键盘通知
- iOS键盘自适应弹出效果
- iOS开发笔记--UILabel和UITextView自适应文本高度代码
- 【代码笔记】iOS-自定义弹出框
- 【代码笔记】iOS-屏幕根据键盘自动的变化高度
- 【代码笔记】iOS-只让textField使用键盘通知
- 【代码笔记】iOS-屏幕根据键盘自动的变化高度
- 【代码笔记】iOS-UILable高度自适应(sizeWithFont)
- iOS开发笔记--UILabel和UITextView自适应文本高度代码
- iOS开发笔记(五):禁止键盘弹出时UIWebView自动滑动
- ios学习笔记---用View动画仿UC浏览器菜单栏弹出效果
- 键盘定制iOS学习笔记9-软键盘的隐藏
- iOS学习笔记11—代码里打印程序所占用的内存
- iOS UITextField 获得焦点后,阻止弹出键盘事件,显示时间选择器
- [iOS代码] 获取键盘keyboard所占区域大小,调整界面布局