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

在 textView 輸入時避免鍵盤遮擋內容

編輯:iOS 開發綜合

螢幕空間本來就不大,一旦鍵盤彈出,往往會遮住下半部內容,讓使用者只能「盲打」。解決這個問題的基本思路很簡單:註冊通知,持續監聽鍵盤事件,鍵盤出現時把編輯區上移(或增加底部內縮),鍵盤消失時再復原。以下用 UITextView 示範。

首先在 viewDidLoad 建立 textView:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.textView = [[UITextView alloc] initWithFrame:self.view.frame];
    self.textView.text = @"請輸入文字";
    [self.view addSubview:self.textView];
}

接著在 viewWillAppear 註冊兩個通知,分別監聽鍵盤出現與消失:

- (void)viewWillAppear:(BOOL)animated
{
    // 監聽鍵盤出現
    [[NSNotificationCenter defaultCenter] addObserver:self
                              selector:@selector(handleKeyboardDidShow:)
                                name:UIKeyboardDidShowNotification
                                object:nil];
    // 監聽鍵盤消失
    [[NSNotificationCenter defaultCenter] addObserver:self
                              selector:@selector(handleKeyboardDidHidden)
                                name:UIKeyboardDidHideNotification
                                object:nil];
    [super viewWillAppear:YES];
}

鍵盤出現時,從通知中取出鍵盤高度,並用它設定 textView 的底部內縮:

- (void)handleKeyboardDidShow:(NSNotification*)paramNotification
{
    // 取得鍵盤高度
    NSValue *keyboardRectAsObject = [[paramNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect;
    [keyboardRectAsObject getValue:&keyboardRect];
    self.textView.contentInset = UIEdgeInsetsMake(0, 0, keyboardRect.size.height, 0);
}

鍵盤消失時,把內縮重設為零即可復原:

- (void)handleKeyboardDidHidden
{
    self.textView.contentInset = UIEdgeInsetsZero;
}

最後別忘了在 viewDidDisappear 中移除观察者,避免内存洩漏:

- (void)viewDidDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

透過 contentInset 的動態調整,就能讓文字輸入區始終保持在鍵盤上方,徹底告別盲打的窘境。

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