这篇文章主要介绍了iOS如何实现防键盘遮挡,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
创新互联建站主营平桂网站建设的网络公司,主营网站建设方案,手机APP定制开发,平桂h5小程序开发搭建,平桂网站营销推广欢迎平桂等地区企业咨询当我们在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如何实现防键盘遮挡”这篇文章对大家有帮助,同时也希望大家多多支持创新互联建站,关注创新互联网站建设公司行业资讯频道,更多相关知识等着你来学习!
另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。