当键盘挡住了视图的两种解决方法

1.平移整个界面(不推荐)

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    // 获得textField坐标和View的中间比较
    CGFloat height = self.labelTextViewAccount.center.y - self.view.frame.size.height / 2.0;
   // 如果大于0,说明键盘遮住了控件,就将整个界面向上平移
    if(height > 0){
        self.view.center = CGPointMake(self.view.center.x, self.view.center.y - height);
    }
    return YES;
}

2.使用动画的方式移动控件(推荐)

  // 

    self.view.backgroundColor = [UIColor cyanColor];
    
    self.myView = [[UIView alloc] initWithFrame:CGRectMake(100, 600, 200, 50)];
    self.myView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.myView];
    
    
    self.textField= [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 150, 50)];
    self.textField.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.textField];

    // 监听键盘的弹起和回收
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillDiapper:) name:UIKeyboardWillHideNotification object:nil];
    

// 实现弹起和收缩方法
    // 键盘弹起的时候触发的方法
- (void)keyBoardWillAppear:(NSNotification *)notification{
    NSLog(@"键盘弹起了");
    // 找到键盘的尺寸
    CGRect rect = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    // 整体打印结构体的方法
    NSLog(@"%@",NSStringFromCGRect(rect));
    
    // 用UIView的动画,让视图随键盘上移
    [UIView animateWithDuration:0.2 animations:^{
        self.myView.frame = CGRectMake(100, 600 - rect.size.height, 200, 50);
    }];
}
// 点击空白处,回收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [super touchesBegan:touches withEvent:event];
    
    [self.textField resignFirstResponder];
}
// 键盘回收的时候触发的方法
- (void)keyBoardWillDiapper:(NSNotification *)notification{
    NSLog(@"键盘回收了");
    
    // 通过UIView动画,让视图回收
    [UIView animateWithDuration:0.2 animations:^{
        self.myView.frame = CGRectMake(100, 600, 200, 50);
    }];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值