iOS 獲取鍵盤彈出高度,動畫時間和動畫路徑曲線

系統對鍵盤的活動有幾個通知的key

UIKeyboardWillShowNotification//鍵盤將要彈起
UIKeyboardDidShowNotification//鍵盤已經彈起
UIKeyboardWillHideNotification//鍵盤將要收起
UIKeyboardDidHideNotification//鍵盤已經收起

我們可以通過這幾個key來接收鍵盤活動的通知

//監聽鍵盤活動
- (void)addNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

在通知的userinfo中包含了鍵盤動畫的所有信息

notification.userInfo
{
    UIKeyboardAnimationCurveUserInfoKey = 7;//動畫曲線類型  
    UIKeyboardAnimationDurationUserInfoKey = "0.25";//動畫持續時間 
    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {414, 226}}";//鍵盤的bounds
    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {207, 849}";//鍵盤動畫起始時的中心點  
    UIKeyboardCenterEndUserInfoKey = "NSPoint: {207, 623}";//鍵盤動畫結束時的中心點  
    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 736}, {414, 226}}";//鍵盤動畫起始時的frame
    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 510}, {414, 226}}";//鍵盤動畫結束時的frame
    UIKeyboardIsLocalUserInfoKey = 1;//鍵盤是否顯示,bool類型,1 show,2 hide
}
- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGRect frame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];//鍵盤動畫結束時的frame
    NSTimeInterval timeInterval = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];//動畫持續時間
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];//動畫曲線類型
    //your animation code
    __weak typeof(self) weakself = self;
    [UIView setAnimationCurve:curve];
    [UIView animateWithDuration:timeInterval animations:^{
        //code
    }];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    CGRect frame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];//鍵盤動畫結束時的frame
    NSTimeInterval timeInterval = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];//動畫持續時間
    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];//動畫曲線類型
    //your animation code
    __weak typeof(self) weakself = self;
    [UIView setAnimationCurve:curve];
    [UIView animateWithDuration:timeInterval animations:^{
        //code
    }];
}

最后把上面代碼中重復部分抽出來就好了

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容