IOS TextField伴随键盘移动

来源:互联网 发布:淘宝客服月度工作总结 编辑:程序博客网 时间:2024/05/09 23:24

这篇文章介绍的是一个简单而又实用的小方法。

我想对于登陆时的一些效果大家应该都不会陌生。

今天就介绍一下,当开始输入TextField文本时键盘弹出TextField伴随键盘移动的实现。

先看一下演示效果

 

我们对TextFiel进行约束。约束内容如下⬇️

约束结束后,我们需要做一个很重要的是,就是把把TextField的底部约束拖到相应的代码区域。

内容如下⬇️

做完这些我们就可以通过代码实现响应的内容

实现代码如下:

复制代码
////  ViewController.m//  CX TextFiled伴随键盘移动的实现////  Created by ma c on 16/3/31.//  Copyright © 2016年 xubaoaichiyu. All rights reserved.//#import "ViewController.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];    //简历通知    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];}-(void)keyboardWillChangeFrameNotification:(NSNotification *)note{    //获取键盘的饿frame    CGRect frmae = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];        //让TextFiled的底部约束间距为屏幕高度减去键盘顶部的y值即可    //注意 这里不要使其等于键盘的高度,因为高度时死的,会导致键盘下去后,TextField并未下去的结果。    self.bottomSpace.constant = [UIScreen mainScreen].bounds.size.height - frmae.origin.y;        //获取键盘的动画时间,使TextField与键盘的形态一致    CGFloat interval = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];    //设置Text的动画    [UIView animateWithDuration:interval animations:^{               //注意这里不是改变值,之前已经改变值了,        //在这里需要做的事强制布局        [self.view layoutIfNeeded];            }];    }-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{        [self.view endEditing:YES];    }@end
复制代码

 

原创粉丝点击