1. 程式人生 > >iOS鍵盤彈出完美移動控制元件

iOS鍵盤彈出完美移動控制元件

新增監聽(最好放在ViewWillAppear裡, 在檢視將要消失時移除監聽)

這裡監聽鍵盤Frame的變化而不是監聽鍵盤的顯示和隱藏

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];

實現方法 _toolBar是要移動的View控制元件
#pragma mark - 鍵盤Frame改變時呼叫
-(void)keyboardFrameChange:(NSNotification *)note
{
    CGFloat durtion = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];

    CGRect frame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    if (frame.origin.y == self.view.frame.size.height)
    {
        // 沒有彈出鍵盤
        [UIView animateWithDuration:durtion animations:^{

            _toolBar.transform = CGAffineTransformIdentity;
        }];
    }
    else
    {
        // 彈出鍵盤
        // 工具條向上移動鍵盤的高度
        [UIView animateWithDuration:durtion animations:^{

            _toolBar.transform = CGAffineTransformMakeTranslation(0, -frame.size.height);
        }];
    }
}