2012-06-22 52 views
2

我有一個UITableView自定義UITableViewCells,他們每個人都有一個UITextField。我爲每個textField分配一個值爲:indexPath.row + 100的標籤。從UITableViewCells更新UITextFields而不重新加載數據

好了,我要更新每個文本字段的每個細胞,當我輸入一個特定的文本框的東西。更清楚的是,當我鍵入一個數字時,我的視圖控制器應該進行一些計算,然後將結果分配給所有其他textFields,並且每次修改textField中的文本時都要執行此操作,假設我鍵入1(進行一些計算並將結果分配給textFields),然後我輸入2,現在計算的數字是12,依此類推。

的問題是,我可以的tableView reloaddata而不關閉keyboar。系統會自動隱藏UIKeyboard,所以在這種情況下reloaddata不起作用。

我試圖用一個NSMutableArray來存儲所有這些文本框,但他們得到了很多,從的cellForRowAtIndexPath當添加他們。

我怎樣才能正確地更新所有這些UITextFields

回答

1

需要更新唯一可見的細胞,但不是所有的人。 假設含量的計算式很簡單:

-(NSString*) textForRowAtIndex:(int)rowIndex 
{ 
    return [NSString stringWithFormat:@"%d", startRowValue + rowIndex]; 
} 

而且每個細胞包含UITextField對象與標籤indexPath.row + 100

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString* cellId = @"cellId"; 
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellId]; 
    if(!cell) 
    { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease]; 
     cell.selectionStyle = UITableViewCellSelectionStyleNone; 
     UITextField* tf = [[[UITextField alloc] initWithFrame:CGRectMake(10, 8, 280, 30)] autorelease]; 
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChange:) 
                name:UITextFieldTextDidChangeNotification object:tf]; 
     tf.delegate = (id)self; 
     [cell.contentView addSubview:tf]; 
    } 

    UITextField* tf = (UITextField*)[[cell.contentView subviews] lastObject]; 
    tf.tag = indexPath.row + 100; 
    tf.text = [self textForRowAtIndex:indexPath.row]; 

    return cell; 
} 

然後所有可見細胞在textFieldTextDidChange:方法進行更新:

-(void) textFieldTextDidChange:(NSNotification*)notification 
{ 
    UITextField* editedTextField = (UITextField*)[notification object]; 
    int editedRowIndex = editedTextField.tag - 100; 
    int editedValue = [editedTextField.text intValue]; 
    startRowValue = editedValue - editedRowIndex; 

    for (NSIndexPath* indexPath in [self.tableView indexPathsForVisibleRows]) 
    { 
     if(indexPath.row != editedRowIndex) 
     { 
      UITableViewCell* cell = [self.tableView cellForRowAtIndexPath:indexPath]; 
      UITextField* textField = (UITextField*)[cell.contentView viewWithTag:indexPath.row+100]; 
      textField.text = [self textForRowAtIndex:indexPath.row]; 
     } 
    } 
} 

允許有50個細胞:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return 50; 
} 

並讓隱藏鍵盤時,完成編輯:

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{ 
    [textField resignFirstResponder]; 
    return YES; 
} 

享受!

相關問題