iOS鍵盤自適應(yīng)彈出效果
更新時間:2017年06月30日 15:53:30 作者:弦外雨
這篇文章主要為大家詳細介紹了iOS鍵盤自適應(yīng)彈出效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下
一、iOS鍵盤自適應(yīng)彈出效果圖
二、工程圖
三、代碼
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
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
iOS10添加本地推送(Local Notification)實例
這篇文章主要為大家詳細介紹了iOS10添加本地推送(Local Notification)實例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09淺述iOS11 Xcode 9 按住command 單擊 恢復到從前(直接跳轉(zhuǎn)到定義)
這篇文章主要介紹了 iOS11 Xcode 9 按住command 單擊 恢復到從前(直接跳轉(zhuǎn)到定義)的相關(guān)資料,需要的朋友可以參考下2017-10-10Objective-C 自定義漸變色Slider的實現(xiàn)方法
系統(tǒng)提供UISlider,但在開發(fā)過程中經(jīng)常需要自定義,本次需求內(nèi)容是實現(xiàn)一個擁有漸變色的滑動條,且漸變色隨著手指touch的位置不同改變區(qū)域,這篇文章主要介紹了Objective-C 自定義漸變色Slider,需要的朋友可以參考下2024-07-07