2011-06-18 59 views
1

這一定是一個常見問題...我在表格單元格內有UITextField,我想讓用戶編輯它。但是,當鍵盤出現時,它經常會遮擋文本字段。如何滾動屏幕鍵盤的UITableView單元格?

我試過使用scrollToRowAtIndexPath:atScrollPosition,但令人驚訝的是這不起作用。我試過將UITableViewScrollPosition設置爲{None,Top,Button,Middle}

我失蹤的滾動祕訣是什麼?

謝謝。

回答

-1

那麼,你的表格單元格是否隱藏了你的文本框?你爲什麼想用滾動來解決它?改變將文本字段添加到單元格的方式。

+0

他的問題是,如何避免被隱藏在文本框鍵盤 – kubi

3

祕訣是你必須手動實施這個行爲,這是一個痛苦。

有你要採取的一些步驟:

第1步:註冊鍵盤的通知

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil]; 

} 

第2步:調整內容插圖當鍵盤出現

- (void)keyboardWasShown:(NSNotification *)notification { 
    NSDictionary* info = [notification userInfo]; 
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; 

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0f, 0.0f, kbSize.height, 0.0f); 
    self.tableview.contentInset = contentInsets; 
    self.tableview.scrollIndicatorInsets = contentInsets; 

    [self.scrollView scrollRectToVisible:self.selectedView.frame animated:YES]; 
} 

這假設你已經在你的類中有一個屬性「selectedView」。還有其他的方法可以做到這一點,但最重要的是,您需要知道用戶需要查看哪個視圖。

步驟3:重置你的表視圖時,鍵盤消失

- (void)keyboardWillBeHidden:(NSNotification *)notification { 
    UIEdgeInsets contentInsets = UIEdgeInsetsZero; 
    self.tableview.contentInset = contentInsets; 
    self.tableview.scrollIndicatorInsets = contentInsets; 
} 

第4步:註銷的通知

- (void)viewWillDisappear:(BOOL)animated { 
    [super viewWillDisappear:animated]; 

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil]; 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil]; 
} 
+0

謝謝。我試圖在沒有通知的情況下做類似的事情,當然這不起作用。現在確實如此。 – Starboo

+0

@Starboo不要使用硬編碼值,它將在未來的iOS版本中幾乎肯定會崩潰。如果你的文本區域飛出屏幕,可能是因爲你沒有正確設置'selectedView',但沒有更多的代碼只是猜測。 – kubi

+0

不錯的答案kubi。 – otto