您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要介绍了iOS如何实现键盘自适应弹出效果,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
一、iOS键盘自适应弹出效果图
二、工程图
三、代码
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如何实现键盘自适应弹出效果”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。