2012-01-16 52 views
24

我正在動態創建一個帶有UITextField的表格視圖。將焦點設置爲表格中的UITextField細節

l_textField = [[UITextField alloc] initWithFrame:TextFieldFrame]; 
l_textField.tag = cellRow; 

l_textField.delegate = self; 
l_textField.font = [UIFont boldSystemFontOfSize:14]; 
l_textField.textColor = [UIColor blackColor]; 
[l_textField setEnabled:YES]; 

[cell.contentView addSubview:l_textField]; 

現在我想在用戶觸摸單元格時將焦點放在這個文本字段上。我寫這篇文章

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath { 
    UITextField* field = (UITextField *) [tblView viewWithTag: newIndexPath.row]; 
    [field resignFirstResponder]; 
} 

但這不起作用

回答

59

變化[field resignFirstResponder];[field becomeFirstResponder];

resignFirstResponder用於從文本字段刪除鍵盤(焦點)

+0

沒有happend,我覺得它像becouse我設置tblView.allowsSelection = NO;而且這個事件不會發生。但是,如果我設置tblView.allowsSelection = YES;它只選擇單元格=( – nabiullinas 2012-01-16 17:38:05

+0

我試圖實現這種方法,但這通常不起作用 嘗試將UITextField分配給[textField becomeFirstResponder]必須將選擇設置爲啓用或設置爲YES/true。 – 2014-08-27 07:07:03

1

我面臨同樣的問題在這裏,即使正確使用[field becomeFirstResponder];

我也用標籤來獲取單元格內的對象。你didSelectRowAtIndexPath應該是這樣的,以獲得正確的細胞:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    currentRow = indexPath.row; 

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    UITextField *indexField = (UITextField *)[cell viewWithTag:101]; 
    [indexField becomeFirstResponder]; 
} 

它的工作對我來說就像魅力。

0

斯威夫特3

myTextField.becomeFirstResponder() 

我的代碼。以當前單元格的索引路徑。並獲得下一個indexpath.row的單元格。並呼籲 ** cell1.txtFindings.becomeFirstResponder()**

if let textFieldIndexPath = specsListView.indexPath(for: cell){ 
     let newIndexPath = IndexPath(row: textFieldIndexPath.row + 1, section: 0) 

     if let cell1: SpecsTableViewCell = specsListView.cellForRow(at: newIndexPath) as? SpecsTableViewCell{ 
      cell1.txtFindings.becomeFirstResponder() 
     } 
}