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

iOS 軟鍵盤遮擋 UITableView 輸入框的解法

編輯:iOS 開發綜合

鍵盤彈出後擋住列表底部的輸入框,是聊天類、評論類介面最常見的困擾。處理思路其實很清晰:監聽鍵盤通知、依鍵盤高度縮短列表、滾動到目前編輯的儲存格。

第一步:註冊鍵盤通知

在初始化方法或 viewDidLoad 中註冊,並務必在 dealloc 中移除觀察者,避免懸空指標。

-(id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // 也可以寫在 viewDidLoad 中
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                selector:@selector(keyboardShown:)
                                                    name:UIKeyboardDidShowNotification
                                                  object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                selector:@selector(keyboardHidden:)
                                                    name:UIKeyboardDidHideNotification
                                                  object:nil];
    }
    return self;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                   name:UIKeyboardDidShowNotification
                                                 object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                   name:UIKeyboardDidHideNotification
                                                 object:nil];
}

第二步:通知到來時調整 frame

注意要先把鍵盤座標從視窗座標系轉換到自身視圖座標系,再據此縮短 tableView 高度;鍵盤收起時還原,並加上一點動畫緩衝。

-(void)keyboardShown:(NSNotification*)notification {
    _initialTVHeight = _tableView.frame.size.height;

    CGRect initialFrame = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect convertedFrame = [self.view convertRect:initialFrame fromView:nil];

    CGRect tvFrame = _tableView.frame;
    tvFrame.size.height = convertedFrame.origin.y;
    _tableView.frame = tvFrame;
}

-(void)keyboardHidden:(NSNotification*)notification {
    CGRect tvFrame = _tableView.frame;
    tvFrame.size.height = _initialTVHeight;
    [UIView beginAnimations:@"TableViewDown" context:NULL];
    [UIView setAnimationDuration:0.3f];
    _tableView.frame = tvFrame;
    [UIView commitAnimations];
}

第三步:讓目前編輯的儲存格捲進可視區

延遲 0.5 秒是為了等鍵盤動畫與列表高度調整都完成後再滾動,否則容易捲到一半被 layout 打斷。

-(void)textFieldDidBeginEditing:(UITextField *)textField {
    NSIndexPath* path = [NSIndexPath indexPathForRow:row inSection:section];
    [self performSelector:@selector(scrollToCell:) withObject:path afterDelay:0.5f];
}

-(void)scrollToCell:(NSIndexPath*)path {
    [_tableView scrollToRowAtIndexPath:path
                     atScrollPosition:UITableViewScrollPositionNone
                             animated:YES];
}

這套做法的優點是不依賴任何第三方庫,邏輯一目了然。若你的專案已經導入 IQKeyboardManager 這類成熟方案,也可以直接採用,省去自己維護的負擔。

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