键盘的弹出和隐藏

键盘的弹出和隐藏

标签(空格分隔): 知识补充

—利用通知的方法监听键盘位置的改变

代码:

#import "ViewController.h"

@interface ViewController ()
// 获得TextField属性
@property (weak, nonatomic) IBOutlet UITextField *textField;
// 获得TextField的底部间距属性
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 利用通知,监听键盘的位置
    // 添加监听
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    // 最常用的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)dealloc{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

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

    // 获取键盘的frame
    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // 获得键盘的动画时间
    CGFloat time = [UIKeyboardAnimationDurationUserInfoKey doubleValue];
    // 修改textfield的底部约束(屏幕的高度 - 键盘的最后Y值)
    [UIView animateWithDuration:time animations:^{
        self.bottomSpace.constant = self.view.frame.size.height - frame.origin.y;
        [self.view layoutIfNeeded];
    }];

}

//- (void)keyBoardWillShow:(NSNotification *)note{
//
//    // 取出键盘的frame
//    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
//    // 修改textField的底部约束
//    
//    CGFloat time = [UIKeyboardAnimationDurationUserInfoKey doubleValue];
//    [UIView animateWithDuration:time animations:^{
//        self.bottomSpace.constant = frame.size.height;
//        [self.view layoutIfNeeded];
//    }];
//    
//}
//
//- (void)keyBoardWillHide:(NSNotification *)note{
//
//    CGFloat time = [UIKeyboardAnimationDurationUserInfoKey doubleValue];
//    [UIView animateWithDuration:time animations:^{
//        self.bottomSpace.constant = 0;
//        [self.view layoutIfNeeded];
//    }];
//    
//}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    // 点击屏幕的时候隐藏键盘
//    [self.textField resignFirstResponder];

//    [self.textField endEditing:YES];
    [self.view endEditing:YES];
}

@end
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值