WEB开发网
开发学院手机开发iPhone 开发 完美适应iOS中的键盘高度变化 阅读

完美适应iOS中的键盘高度变化

 2013-04-25 19:24:08 来源:开发学院   
核心提示:#pragma mark - reg & unreg notification- (void)regNotification{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeF
#pragma mark - reg & unreg notification

- (void)regNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)unregNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}

#pragma mark - notification handler

- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;
    
    CGRect inputFieldRect = self.inputTextField.frame;
    CGRect moreBtnRect = self.moreInputTypeBtn.frame;
    
    inputFieldRect.origin.y += yOffset;
    moreBtnRect.origin.y += yOffset;
    
    [UIView animateWithDuration:duration animations:^{
        self.inputTextField.frame = inputFieldRect;
        self.moreInputTypeBtn.frame = moreBtnRect;
    }];
}

通过获取键盘消息的开始状态、结束状态,以及变化周期,可以计算出具体的Y偏移,从而在相同时间里做相同偏移量。 

Tags:完美 适应 iOS

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接