2016-01-18 62 views
1

我有可編輯的自定義(nib)加載可重用UITableViewCell s其中包含UITextView。行是自動調整大小的。我有一個問題,如果用戶開始編輯UITextView,然後開始滾動焦點(firstResponder)仍然保持,我認爲這是一個問題,因爲屏幕單元通常允許被刪除或重用。這會導致問題,因此該行仍保留在內存中,稍後顯示在錯誤的位置。UITableViewCell中的UITextView ResignFirstResponder滾動出屏幕

我認爲這是一個很好的解決方案,當細胞在屏幕外時,請撥打resignFirstResponder來獲得UITextView。然而didEndDisplayingCell似乎並沒有被要求這種情況。我也嘗試過prepareForReuse,它不會被調用。

任何想法?

public func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) 
{ 
    if (tableView.indexPathsForVisibleRows?.indexOf(indexPath) == nil) { 
     if let noteCell = cell as? AgendaNotesTableViewCell { 
      noteCell.noteTextView.resignFirstResponder() 
     } 
    } 
} 

看起來這適用於除了當前firstResponder之外的所有單元。我想這是保存在內存中,因此不會被用來調用didEndDisplayingCell

回答

0

添加UIGestureRecognizerUITableviewviewDidLoad方法,使用它的委託方法之一UITextView

UITapGestureRecognizer * gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeKeyboard)]; 
    [self.tableView addGestureRecognizer:gesture]; 

保持基準

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text 

當點擊桌面視圖時,手勢識別器方法調用,即

- (void)removeKeyboard { 
// set resignFirstResponder to textview 
    } 
+0

這不是我想要的。當你觸摸'UITableView'上的任何地方時,我假設這段代碼隱藏了鍵盤。當單元格滾動到屏幕可見區域外時,我想隱藏鍵盤。 – Sunkas

0

我想出了一個解決方案。它工作正常,但如果有人發現更好的一個,我會將其標記爲正確的。

我在我的視圖控制器中添加了一個變量來跟蹤firstResponder UITextView的當前indexPath。每次我開始編輯UITextView我設置變量,在我的viewController這個方法:

private var currentFirstResponderIndexPath:NSIndexPath? = nil 

public func didSetFirstResponderIndexPath(indexPath:NSIndexPath?) 
{ 
    currentFirstResponderIndexPath = indexPath 
} 

在我的自定義UITableViewCell S:

//MARK: - UITextViewDelegate 

public func textViewDidEndEditing(textView: UITextView) 
{ 
    //.... 
    agendaViewController?.didSetFirstResponderIndexPath(nil) 
} 


public func textViewDidBeginEditing(textView: UITextView) 
{ 
    //... 
    agendaViewController?.didSetFirstResponderIndexPath(indexPath) 
} 

其中agendaViewController是弱指針的viewController。這也可以是一個代表。

然後我檢查其滾動當前firstResponder時不可見:

//MARK: - UIScrollViewDelegate 

public func scrollViewDidScroll(scrollView: UIScrollView) 
{ 
    updateHelperAlphas() 
    if let indexPath = currentFirstResponderIndexPath { 
     let visibleCellIndexPaths = tableView.indexPathsForVisibleRows ?? [] 
     let indexPathForCellWithFirstResponderIsOutOfScreen = !visibleCellIndexPaths.contains(indexPath) 
     if (indexPathForCellWithFirstResponderIsOutOfScreen) { 
      self.view.endEditing(true) 
     } 
    } 
} 

然而,這種解決方案也有一些缺點。如果開始編輯tableview底部的一行,它將顯示鍵盤並隱藏將退出第一響應者的單元,這將隱藏鍵盤et.c.那裏需要更多的邏輯。