您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS TextField 鍵盤自適應:透過通知移動輸入框

編輯:iOS 開發綜合

讓輸入框依鍵盤自動調整位置

在 iOS 中,當鍵盤彈出時,可能會遮住底部的輸入框。為了避免使用者看不到目前輸入位置,App 通常會在鍵盤出現時移動視圖,讓輸入框保持在可見區域。

實作這種效果時,可以監聽 UIKeyboardWillChangeFrameNotification。這個通知會帶回鍵盤動畫資訊,包括動畫時間、起始 frame 與結束 frame。透過比較鍵盤變化前後的位置,就能推算出鍵盤高度與移動方向。

註冊與移除通知

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

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

取得鍵盤變化資訊

在通知回呼中,可以從 userInfo 取出動畫持續時間、鍵盤起始位置與結束位置。兩個 y 值相減,就能得到鍵盤移動的偏移量。

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    NSDictionary *dict = notification.userInfo;
    CGFloat duration = [dict[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect beginKeyboardRect = [dict[UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endKeyboardRect = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;

    // 依 yOffset 判斷鍵盤彈出或收回
}

計算輸入框與螢幕底部的距離

若要讓輸入框在鍵盤上方保持固定間距,可以先計算輸入框底部到螢幕底部的距離,再把視圖 y 軸位置調整對應高度。

UIView *view = appDelegate.window.subviews[array.count - 1];
CGRect selfFrameFromUIWindow = [self convertRect:self.bounds toView:appDelegate.window];
CGFloat bottomHeight = [UIScreen mainScreen].bounds.size.height - selfFrameFromUIWindow.origin.y - selfFrameFromUIWindow.size.height;
CGRect windowFrame = appDelegate.window.frame;
windowFrame.origin.y += yOffset + bottomHeight - 40;

平滑移動視圖

鍵盤彈出與收回通常都有動畫,因此視圖位置變化也應該搭配相同時間的動畫,讓整體體驗更自然。

if (yOffset < 0) {
    [UIView animateWithDuration:duration animations:^{
        view.frame = windowFrame;
    }];
} else {
    [UIView animateWithDuration:duration animations:^{
        view.frame = appDelegate.window.frame;
    }];
}

透過鍵盤通知取得 frame 變化,再讓視圖依輸入框位置移動,就能完成常見的鍵盤自適應效果。實作時要特別注意動畫時間一致,以及不同螢幕尺寸下的位置計算,才能讓體驗穩定。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved