这篇文章主要介绍了iOS如何实现防键盘遮挡,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
创新互联-专业网站定制、快速模板网站建设、高性价比溧阳网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式溧阳网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖溧阳地区。费用合理售后完善,十年实体公司更值得信赖。
当我们在UITextField输入数据时经常弹出键盘遮挡界面,解决方法是:在弹出键盘时将整个UIVIew向上移动,在键盘消失时,UIVIew还原。
实例代码如下:
@interface ViewController ()@property(nonatomic,strong)UITextField* tf; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.tf = [[UITextField alloc]initWithFrame:CGRectMake(10, 600, 100, 20)]; self.tf.delegate = self; self.tf.backgroundColor = [UIColor blackColor]; [self.view addSubview:self.tf]; } #pragma mark life Circle -(void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; //后台切换到前台通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground)name:UIApplicationWillEnterForegroundNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; [self.view endEditing:YES]; } - (void)applicationWillEnterForeground{ [self.view endEditing:YES]; } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ [self.view endEditing:YES]; } #pragma mark UITextFieldDelegate -(void)textFieldDidBeginEditing:(UITextField *)textField{ //第一个cell不往上弹输入框的位置 // if(indexPath.row!=0){ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil]; // } } -(void)textFieldDidEndEditing:(UITextField *)textField{ } #pragma mark 键盘操作 - (void)keyboardWillChange:(NSNotification *)note { NSDictionary *userInfo = note.userInfo; CGFloat duration = [userInfo[@"UIKeyboardAnimationDurationUserInfoKey"] doubleValue]; CGRect keyFrame = [userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue]; //这个64是我减去的navigationbar加上状态栏20的高度,可以看自己的实际情况决定是否减去; CGFloat moveY = keyFrame.origin.y -self.tf.frame.origin.y-self.tf.frame.size.height; NSLog(@"%f",moveY); [UIView animateWithDuration:duration animations:^{ self.view.transform = CGAffineTransformMakeTranslation(0, moveY); }]; } - (void)keyboardWillHide:(NSNotification *)nsnotification { [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil]; [UIView animateWithDuration:0.2 animations:^{ self.view.transform = CGAffineTransformMakeTranslation(0, 0); }]; } @end
感谢你能够认真阅读完这篇文章,希望小编分享的“iOS如何实现防键盘遮挡”这篇文章对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,更多相关知识等着你来学习!