1. 程式人生 > >[作業系統]處理UIScrollView中的編輯框被彈出鍵盤遮擋的問題

[作業系統]處理UIScrollView中的編輯框被彈出鍵盤遮擋的問題

當UIScrollView中的某一行存在編輯框時,點選編輯框,彈出的鍵盤有可能遮擋住編輯框,造成體驗效果很不好。解決的方法很簡單,就是將UIScrollView的內容和UIScrollView容器的內邊距(準確來說是底邊距)增加正好是鍵盤高度的距離,ios系統會將選中的行重新定位,位置正好是距離視窗底邊相同距離的地方,當然,鍵盤縮回去的時候注意要把內邊距再設定回來。涉及到的最主要的函式就是UIScrollView的setContentInset函式。
首先,要在程式開始的地方註冊鍵盤彈出和縮回的通知監聽:[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

keyboardWillShow和keyboardWillHide的實現如下:
- (void)keyboardWillShow:(NSNotification *)notification
{
  //鍵盤彈出後的frame
NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardBounds;
[keyboardBoundsValue getValue:&keyboardBounds];
//設定新的內邊距,這個內邊距是UIScrollView的最後一行距離UIScrollView底邊框的距離,
  //這樣當該函式觸發式,系統會將當前選中行距離視窗底邊的距離設為該值,從而正好不被鍵盤遮蓋住。
UIEdgeInsets e = UIEdgeInsetsMake(0, 0, keyboardBounds.size.height, 0);
[[self tableView] setContentInset:e];

  //調整滑動條距離視窗底邊的距離
[[self tableView] setScrollIndicatorInsets:e];
}

  • (void)keyboardWillHide:(NSNotification *)notification
    {
     //鍵盤縮回後,恢復正常設定
    UIEdgeInsets e = UIEdgeInsetsMake(0, 0, 0, 0);
    [[self tableView] setScrollIndicatorInsets:e];
    [[self tableView] setContentInset:e];
    }
    效果圖如下:
    彈出前:
    這裡寫圖片描述
    彈出後:
    這裡寫圖片描述