您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 如何取得軟鍵盤高度並自動調整輸入框

編輯:iOS 相關資訊

鍵盤高度在不同螢幕尺寸與不同方向下並不相同,寫死數字遲早會出問題。正確做法是用通知取得實際尺寸。

- (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(keyboardDidShow:)
                                                name:UIKeyboardDidShowNotification
                                              object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(keyboardDidHide:)
                                                name:UIKeyboardDidHideNotification
                                              object:nil];
}

- (void)keyboardDidShow:(NSNotification *)nsNotification {
    NSDictionary *userInfo = [nsNotification userInfo];
    _keyboardSize = [[userInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    [self updateTextViewSize];
}

- (void)keyboardDidHide:(NSNotification *)nsNotification {
    _keyboardSize = CGSizeMake(0.0, 0.0);
    [self updateTextViewSize];
}

- (void)updateTextViewSize {
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    CGFloat keyboardHeight = UIInterfaceOrientationIsLandscape(orientation)
                           ? _keyboardSize.width
                           : _keyboardSize.height;
    _textView.frame = CGRectMake(0, 0,
                                 self.view.frame.size.width,
                                 self.view.frame.size.height - keyboardHeight);
}

幾個關鍵點

1. 為何用 FrameBegin 而非 FrameEnd:UIKeyboardFrameBeginUserInfoKey 給的是動畫開始前的目標位置。若你的版面調整也想跟著鍵盤一起動,用它才能對齊動畫節奏;若反而出現抖動,可改試 UIKeyboardFrameEndUserInfoKey。

2. 橫向時要交換寬高:鍵盤的 frame 是相對於螢幕座標的,橫屏時「高度」其實落在 width 上,這就是範例中 UIInterfaceOrientationIsLandscape 判斷的用途。

3. 记得移除 observer:在 dealloc 或 viewDidDisappear 中呼叫 removeObserver:,否則視圖釋放後收到通知會當掉。

4. 更省事的做法:若只是單純的輸入框,直接用 IQKeyboardManager 這類成熟方案即可,它會自動處理鍵盤避讓、previous/next 切換與 return 鍵行為。若使用 iOS 9 以後的 textView 搭配 keyboardLayoutGuide 概念(或用 Auto Layout 的 keyboardLayoutGuide 錨定),也能少寫不少樣板程式。

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