iOS 实现输入框被编辑以及取消编辑跟随键盘移动

来源:互联网 发布:阿里云市场 编辑:程序博客网 时间:2024/05/01 01:46

通常情况下,我们在做评论的时候,以及即时聊天时候要实现实现输入框被编辑以及取消编辑跟随键盘移动。

效果和微信一样,当我们编辑的时候输入框就会跟随键盘移动。

例子效果图:


当我点击评论或者编辑输入框的时候,键盘就会自动上移是实现代码如下:

- (void)viewDidLoad {

    [superviewDidLoad];

     // 收起键盘键盘

    UITapGestureRecognizer *tapgest = [[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(tapBackAction)];

    [self.viewaddGestureRecognizer:tapgest];

}


- (void)tapBackAction {

    [self.viewendEditing:YES];

}


- (void)viewWillAppear:(BOOL)animated {

    // 添加对键盘的监控

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyBoardWillShow:)name:UIKeyboardWillShowNotificationobject:nil];

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(keyBoardWillHide:)name:UIKeyboardWillHideNotificationobject:nil];

}


- (void)tapBackAction {

    [self.viewendEditing:YES];

}


- (void)keyBoardWillShow:(NSNotification *) note {

    // 获取用户信息

    NSDictionary *userInfo = [NSDictionarydictionaryWithDictionary:note.userInfo];

    // 获取键盘高度

    CGRect keyBoardBounds  = [[userInfoobjectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

    CGFloat keyBoardHeight = keyBoardBounds.size.height;

    // 获取键盘动画时间

    CGFloat animationTime  = [[userInfoobjectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];

    

    // 定义好动作

    void (^animation)(void) = ^void(void) {

        self.suspendView.transform = CGAffineTransformMakeTranslation(0, - keyBoardHeight);

    };

    

    if (animationTime >0) {

        [UIViewanimateWithDuration:animationTimeanimations:animation];

    } else {

        animation();

    }

    

}


- (void)keyBoardWillHide:(NSNotification *) note {

    // 获取用户信息

    NSDictionary *userInfo = [NSDictionarydictionaryWithDictionary:note.userInfo];

    // 获取键盘动画时间

    CGFloat animationTime  = [[userInfoobjectForKey:UIKeyboardAnimationDurationUserInfoKey]floatValue];

    

    // 定义好动作

    void (^animation)(void) = ^void(void) {

        self.suspendView.transform = CGAffineTransformIdentity;

    };

    

    if (animationTime >0) {

        [UIViewanimateWithDuration:animationTimeanimations:animation];

    } else {

        animation();

    }

}


self.suspendView就是textfild后面的UIView。

@property (weak,nonatomic)IBOutletUIView *suspendView;


这样就实现了,所需要的效果

阅读全文
0 0
原创粉丝点击