2012-12-24 40 views
1

我創建了一個表格,它動態地創建了自定義的包含textField的單元格。當我運行程序時,我可以將文本輸入到textFields中。但是,在退出程序/切換到不同的viewController之前,我無法收集輸入到它們中的文本。你能否建議我應該怎麼做才能提取用戶輸入的文字。訪問嵌入單元格中的textField

我知道我可以使用下面的代碼訪問細胞...

for (int section = 1; section < [self.tableView numberOfSections]; section++) // section 0: profile picture 
{ 
    for(int row = 0; row < [self.tableView numberOfRowsInSection:section]; row++) 
    { 
     NSLog(@"section = %d, row = %d", section, row); 
     NSIndexPath *tempIndexPath = [NSIndexPath indexPathForRow:row inSection:section]; 
     UITableViewCell *tempCell = [self tableView:self.tableView cellForRowAtIndexPath:tempIndexPath]; 
//   NSLog(@"tempCell = %@", tempCell); 

    } 
} 

但我不能夠提取其中所含的文本。

我也提到:Accessing UITextField in a custom UITableViewCell。但我正在尋找更清潔的解決方案。

謝謝!

+0

你有沒有試着與吸氣二傳手的文本框,在自定義單元格類使用@屬性,以及訪問這些使用tempcell .yourtextfield.text。 – josh

回答

1

您引用的鏈接與您需要執行的操作非常接近,但是有更好的方法來獲取indexPath。

從iOS編程入手時,一個常見的錯誤概念是您需要在需要數據時獲取文本字段的所有值(例如用戶點擊「提交」時)。這個問題,特別是當他們在一個表中時,是文本字段並不總是可用的。如果單元格離開屏幕,它很可能不存在,或者它已被重用在表格的不同行中。文本字段是查看的這應該是顯示數據,而不是您存儲它的模型。

所以,你需要做的第一件事就是讓你的視圖控制器符合UITextFieldDelegate協議,當你創建設置文本字段的委託到您的視圖控制器:

你.h文件中(該<UITextFieldDelegate>是其中的重要組成部分):

@interface YourViewController : UIViewController <UITextFieldDelegate> 

當您創建文本字段:

myNewTextfield.delegate = self; 

這告訴文本領域來通知您重要的變化。現在,你只需要儘快建立被稱爲文本字段的委託方法,因爲他們完成編輯文本字段,並等待它被調用,這樣就可以存儲文本:

- (void) textFieldDidEndEditing:(UITextField *)textField { 
    // If you need the index path of the table view cell which contains the text field in order to know how to store it, use: 
    CGRect position = [self convertRect:textField.frame toView:self.tableView]; 
    NSArray *indexPaths = [self.tableView indexPathsForRowsInRect:position]; 
    NSIndexPath *indexPath = [indexPaths objectAtIndex:0]; 

    // Save the contents of the text field somewhere so that you have it later when you need it: 
    something = textField.text; 
} 
0

This教程對我有幫助。你可以通過標籤來引用你需要的任何對象。

在故事板拖動UIImageViewUITextField等,並將標記設置爲100(無論你想要什麼),然後在你的- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath使用標記來引用它。

這裏的東西你可以做,只記得設置標籤的故事板:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"Cell"; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

// Configure the cell... 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 

UITextField *tField = (UITextField *)[cell viewWithTag:100]; 

return cell; 
}