iOS解决键盘遮挡问题

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    for(int i = 0; i < 10; i++)
    {
    UITextField textF = [[UITextField alloc] initWithFrame:CGRectMake(20, 50 i + 50, 200, 45)];
    textF.borderStyle = UITextBorderStyleRoundedRect;
    textF.delegate = self;
    textF.placeholder = [NSString stringWithFormat:@”第%d个textField”,i];
    [self.view addSubview:textF];
    }

    //频道:UIKeyboardWillShowNotification 监听键盘即将升起
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    //键盘收起的时候
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHidden) name:UIKeyboardWillHideNotification object:nil];
    }

  • (void)keyboardWillShow:(NSNotification *)noti
    {
    //键盘最后停止时候的高度

    //得到键盘的信息
    NSDictionary *dic = noti.userInfo;

    //键盘停止时候的值
    NSValue *keyBoardValue = [dic objectForKey:UIKeyboardFrameEndUserInfoKey];

    //转为CGRect变量
    CGRect keyBoardFrame = keyBoardValue.CGRectValue;

    //1.获取textField底部y坐标
    //2.算textField和键盘y坐标的差值
    //差值代表被遮住的部分
    NSInteger offset = _selectTextF.frame.origin.y + _selectTextF.frame.size.height - keyBoardFrame.origin.y;

    //如果遮住
    if (offset > 0) {
    //视图上移动差值
    self.view.frame = CGRectMake(0, -offset, self.view.frame.size.width, self.view.frame.size.height);
    }

}

  • (void)keyboardWillHidden
    {
    //键盘即将下落的时候,让self.view回到起始位置
    self.view.frame = self.view.bounds;
    }

  • (void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event
    {
    [self.view endEditing:YES];
    }

  • (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
    {
    _selectTextF = textField;
    return YES;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值