登入頁、評論頁、任何有輸入框的畫面,幾乎都會遇到同一個問題:鍵盤彈出來,正好把輸入框擋住,使用者看不到自己在打什麼。解法是監聽鍵盤的顯示與隱藏通知,在鍵盤出現時把整個視圖往上推。
先看成果:



#import "ViewController.h"
#import "UIView+FrameExtension.h" // 自行封裝的 frame 便捷存取
#define kDeviceHeight [UIScreen mainScreen].bounds.size.height
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor lightGrayColor];
// 第一個輸入框
UITextField *firstField = [[UITextField alloc] initWithFrame:CGRectMake(50, 300, 200, 40)];
firstField.backgroundColor = [UIColor whiteColor];
[self.view addSubview:firstField];
// 第二個輸入框,位置依第一個推算
UITextField *secondField = [[UITextField alloc] initWithFrame:CGRectMake(firstField.x,
firstField.bottom + 50,
firstField.width,
firstField.height)];
secondField.backgroundColor = [UIColor whiteColor];
[self.view addSubview:secondField];
// 註冊鍵盤顯示通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(showKeyboard:)
name:UIKeyboardWillShowNotification
object:nil];
// 註冊鍵盤隱藏通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(hideKeyboard:)
name:UIKeyboardWillHideNotification
object:nil];
}
#pragma mark - 鍵盤彈出
- (void)showKeyboard:(NSNotification *)notification {
// 找出目前正在編輯的輸入框
UITextField *txtField;
for (UIView *subView in self.view.subviews) {
if ([subView isKindOfClass:[UITextField class]]) {
UITextField *tempField = (UITextField *)subView;
if (tempField.isEditing) {
txtField = tempField;
break;
}
}
}
// 從通知中取出鍵盤資訊
NSDictionary *userInfoDict = notification.userInfo;
NSValue *value = [userInfoDict objectForKey:UIKeyboardBoundsUserInfoKey];
CGSize keyboardSize = [value CGRectValue].size;
CGFloat keyboardHeight = keyboardSize.height;
// 計算輸入框底部與鍵盤頂部的距離
CGFloat offset = kDeviceHeight - keyboardHeight - txtField.bottom;
if (offset < 0) {
// 會被遮住,往上推(多留一點間距比較好看)
offset = offset - 10;
[UIView animateWithDuration:0.5 animations:^{
self.view.transform = CGAffineTransformMakeTranslation(0, offset);
}];
}
}
#pragma mark - 鍵盤隱藏
- (void)hideKeyboard:(NSNotification *)notification {
[UIView animateWithDuration:2 animations:^{
self.view.transform = CGAffineTransformIdentity;
}];
}
#pragma mark - 點空白處收起鍵盤
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
@end
邏輯可以拆成三塊:
隱藏時把 transform 還原成 CGAffineTransformIdentity,視圖就回到原位。
這份範例能跑,但若要用在正式專案,有幾處建議調整:
UIKeyboardAnimationDurationUserInfoKey 與 UIKeyboardAnimationCurveUserInfoKey,讓視圖位移與鍵盤動畫完全同步。removeObserver:,避免通知殘留造成重複觸發。如果輸入框嵌在 UIScrollView 裡( UITableView 也適用),其實不必自己算位移。只要把 scrollView 的 contentInset.bottom 設為鍵盤高度,並把當前輸入框 scrollRectToVisible:animated:,系統就會自動處理捲動與邊界,比手動改 transform 穩健得多,也不會出現「視圖被推出螢幕外」的窘境。
若使用 Auto Layout,另一個常見策略是為頂部約束建立一個 IBOutlet,在鍵盤通知中更新 constant 並呼叫 layoutIfNeeded,同樣能達到平滑過渡的效果。