要讓輸入框在鍵盤彈出時自動上移,最可靠的方式是監聽鍵盤的通知,從通知中取得真實的鍵盤高度,再依此調整面板位置。以下是一份完整實作。
- (id)init
{
self = [super init];
if (self) {
self.wantsFullScreenLayout = YES;
[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackTranslucent;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillChangeFrame:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillChangeFrame:)
name:UIKeyboardWillHideNotification
object:nil];
}
return self;
}這裡有個關鍵設計:顯示與隱藏兩個通知共用同一個 handler。原因是鍵盤收起時同樣會觸發 keyboardWillChangeFrame:,此時通知裡的 keyboardBounds 高度會是 0,用同一段程式碼就能處理「往上推」與「復位」兩種情況,不必寫兩套邏輯。
-(void)loadview
{
titlefield.delegate = self;
}#pragma mark -
#pragma mark - textfield delegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
[self adjustPanelsWithKeybordHeight:0];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
NSLog(@"should return");
[self.sendpanel.titlefield resignFirstResponder];
return YES;
}textFieldDidEndEditing: 中傳入高度 0,等於告訴版面「鍵盤已經不在了,全部復位」。而 textFieldShouldReturn: 則透過 resignFirstResponder 讓鍵盤收起,收起的過程會觸發 WillHide 通知,進而呼叫到同一個調整方法。
- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
NSLog(@"keyboardWillChangeFrame");
NSValue *keyboardBoundsValue =
[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardBounds;
[keyboardBoundsValue getValue:&keyboardBounds];
NSLog(@"height = %f", keyboardBounds.size.height);
[self adjustPanelsWithKeybordHeight:keyboardBounds.size.height];
}重點是 UIKeyboardFrameEndUserInfoKey。用 End 而非 Begin,是因為 Begin 給的是動畫開始前的 frame,End 才是最終位置,也就是真正會遮住畫面的高度。
-(void)adjustPanelsWithKeybordHeight:(float)height
{
sendpanel.frame = CGRectMake(0, 435 - height,
sendpanel.frame.size.width,
sendpanel.frame.size.height);
progresspanel.frame = CGRectMake(0, 400 - height,
progresspanel.frame.size.width,
progresspanel.frame.size.height);
}把所有需要上移的面板 y 座標都減去鍵盤高度,鍵盤收起時傳入 0,座標自然就回到原位。
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillHideNotification
object:nil];
}在 MRC 時代漏掉這一步會導致 notification 送給已釋放的物件而崩潰,是極常見的錯誤。ARC 之下雖然編譯器會幫忙,但養成成對處理的習慣仍然重要。
示範中的 435 與 400 是寫死的座標,只在特定螢幕尺寸下正確。實務上有兩個更穩健的方向:
另外,鍵盤高度不只依裝置而異,也依鍵盤類型(英文、注音、九宮格、含表情符號)而不同,這正是「一定要從通知取實際高度、不要寫死數字」的根本原因。