2015-08-25 2 views
1

Проблема, с которой я сталкиваюсь, заключается в том, что когда я просматриваю свое табличное представление, если текстовые поля пустые (и показывает значение-заполнитель), строки показывают, что соответствующее значение-заполнитель просто отлично. Однако, если я начну просматривать представление таблицы и вводить текст внутри текстовых полей, как только я прокручу вниз, предыдущие значения текстового поля начнут отображаться в других текстовых полях ниже в таблице. Я предполагаю, что это имеет какое-то отношение к идентификатору ячейки, но, похоже, это отлично работает с моими ярлыками и заполнителем uitextfield, а не текстовым вводом текста текстового поля. Есть предположения? Вот код ...Текстовое поле в ячейке tableview изменяет текстовое значение

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

    CustomCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    cell.headerLabel.text = @"some string"; 
    cell.textField.placeholder = @"some other string placeholder,"; 
    cell.textField.delegate = self; 

    return cell; 
} 

А вот CustomCell

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{ 
    if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]){ 
     headerLabel =[[UILabel alloc] initWithFrame:CGRectZero]; 
     headerLabel.translatesAutoresizingMaskIntoConstraints = NO; 
     headerLabel.textColor = [UIColor colorWithRed:155.0/255.0 green:155.0/255.0 blue:155.0/255.0 alpha:1.0]; 
     headerLabel.font = [UIFont fontWithName:@"Helvetica Neue Reg" size:15]; 

     textField = [[UITextField alloc] initWithFrame:CGRectZero]; 
     textField.textColor = [UIColor colorWithRed:13.0/255.0 green:122/255.0 blue:255.0/255.0 alpha:1.0]; 
     textField.translatesAutoresizingMaskIntoConstraints = NO; 
     textField.font = [UIFont fontWithName:@"Helvetica Neue" size:15]; 

     [self.contentView addSubview:headerLabel]; 
     [self.contentView addSubview:textField]; 

     [self.contentView addConstraint: [NSLayoutConstraint constraintWithItem:headerLabel 
               attribute:NSLayoutAttributeLeading 
               relatedBy:NSLayoutRelationEqual 
               toItem:self.contentView 
               attribute:NSLayoutAttributeLeading 
              multiplier:1 
               constant:27 ] ] ; 

     [self.contentView addConstraint: [NSLayoutConstraint constraintWithItem:headerLabel 
               attribute:NSLayoutAttributeTop 
               relatedBy:NSLayoutRelationEqual 
               toItem:self.contentView 
               attribute:NSLayoutAttributeTop 
              multiplier:1 
               constant:10 ] ] ; 

     [self.contentView addConstraint: [NSLayoutConstraint constraintWithItem:textField 
               attribute:NSLayoutAttributeLeading 
               relatedBy:NSLayoutRelationEqual 
               toItem:self.contentView 
               attribute:NSLayoutAttributeLeading 
              multiplier:1 
               constant:27 ] ] ; 

     [self.contentView addConstraint: [NSLayoutConstraint constraintWithItem:textField 
               attribute:NSLayoutAttributeTop 
               relatedBy:NSLayoutRelationEqual 
               toItem:headerLabel 
               attribute:NSLayoutAttributeBottom 
              multiplier:1 
               constant:5 ] ] ; 

     [self.contentView addConstraint: [NSLayoutConstraint constraintWithItem:textField 
               attribute:NSLayoutAttributeTrailing 
               relatedBy:NSLayoutRelationEqual 
               toItem:self.contentView 
               attribute:NSLayoutAttributeTrailing 
              multiplier:1 
               constant:-27 ] ] ; 

    } 

    return self; 
} 
+0

Вам нужно сохранить текст, как он меняется, и вы должны установить каждый текст поле 'text' в методе' cellForRowAtIndexPath: '. – rmaddy

ответ

0

Вы предоставляете источник данных подкладочный для вашего представления таблицы? Причина, по которой вы столкнулись с этой проблемой, связана с тем, что

[self.tableView dequeueReusableCellWithIdentifier: CellIdentifier];

Этот метод повторно использует ваши ячейки, и поскольку вы не связаны текстом с указательным путем, ячейка повторно используется, но сохраняет текст, который вы добавили к нему ранее в своей метке.

Так вот как вы можете это исправить. Предположим, вы вводите текст в текстовое поле. Вам нужно сохранить эти данные (обычно я использую массив) и соответствовать его свойствам cellPlayer.row ячейки, в которую было изменено текстовое поле. Затем tableview использует этот источник данных для заполнения ярлыков в ячейках.

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

    CustomCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    cell.headerLabel.text = @"some string"; 

    //Using your data source array to get your data for each cell 
    cell.textField.text = self.myDataSourceTextArray[indexPath.row]; 
    cell.textField.delegate = self; 

    return cell; 
} 

Более сложная часть будет связывать текстовое поле с определенным указательным путем. Я бы сделал отдельные ячейки делегатом для текстового поля, а затем сам ядро ​​обновил ваш источник данных всякий раз, когда их текстовое поле обновляется и передает их отдельные пути индекса, чтобы вы могли сохранить текст для правильных ячеек.

0

В моем случае я хочу, чтобы уменьшить значение TextField в Tableview с помощью кнопки действия, которые презентуют на тот же клетку

-(void)decreaseCount:(id)sender 
{ 
    UIButton *btn = (UIButton *)sender; 

    UITableViewCell *cell = (UITableViewCell *) [[btn superview]superview]; 

    NSIndexPath *path = [tableView indexPathForCell:cell]; 

    UITextField *tempText = (UITextField *)[cell viewWithTag:10]; 

    if ([tempText.text integerValue] >0) { 
     tempText.text = [NSString stringWithFormat:@"%ld",[tempText.text integerValue]-1]; 

    } 

    // in my case I want to update Array 
    [self updateArray: btn.tag :tempText.text]; 

} 

// here i have replace the array object as per my need 
-(void)updateArray:(int) index :(NSString *)str 
{ 
    NSMutableArray * arrayCount = [[NSMutableArray alloc]init]; 
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init]; 
    [dict setValue:str forKey:@"count"]; 
    [arrayCount replaceObjectAtIndex:index withObject:dict]; 

} 
Смежные вопросы