美文网首页
ios-键盘上移

ios-键盘上移

作者: 紫嫣沁 | 来源:发表于2017-07-19 14:53 被阅读0次

    1,两个通知

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:)name:UIKeyboardWillHideNotification object:nil];

    2,实现两个方法:

    //键盘弹出

    -(void)keyboardWillShow:(NSNotification *)n

    {

    NSDictionary* userInfo = [n userInfo];

    //UIKeyboardFrameEndUserInfoKey 要用这个key,别用错啦!!

    CGSize keyboardSize =[[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size;

    CGRect frame = self.editAlert.frame;

    NSInteger offset = frame.origin.y+frame.size.height - (kScreenHeight - keyboardSize.height);//键盘高度216

    NSTimeInterval animationDuration = 0.30f;

    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];

    [UIView setAnimationDuration:animationDuration];

    if(offset >= 0)

    {

    self.editAlert.sd_y = kScreenHeight - keyboardSize.height - self.editAlert.sd_height;

    }

    [UIView commitAnimations];

    }

    //键盘隐藏

    -(void)keyboardWillHide:(NSNotification *)n

    {

    NSTimeInterval animationDuration = 0.30f;

    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];

    [UIView setAnimationDuration:animationDuration];

    CGRect rect = CGRectMake(58.0f, (kScreenHeight-180)/2, kScreenWidth-58*2, 180);

    self.editAlert.frame = rect;

    [UIView commitAnimations];

    [self.ContentText resignFirstResponder];

    _keyboardIsShown= NO;

    }

    3,记得在dealloc中移除通知:

    -(void)dealloc

    {

    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:self.ContentText];

    }

    相关文章

      网友评论

          本文标题:ios-键盘上移

          本文链接:https://www.haomeiwen.com/subject/apulkxtx.html