在UitableView中使用时,UiTextField会创建数据混乱。

时间:2016-04-23 10:16:14

标签: ios uitableview

我用一个textField创建了一个简单的UITableViewCell。我给它1000标签,以便我可以从我的cellForRowAtIndexPath访问它,我还预装了一些数据,如

- (void)viewDidLoad {
      [super viewDidLoad];
      _data = [[NSMutableArray alloc] init];
      [_data addObject:@"Hassan"];
      [_data addObject:@"Malik"];
      [_data addObject:@""];
      [_data addObject:@"dsldjsd"];
      [_data addObject:@""];
      [_data addObject:@"Halsda"];
      [_data addObject:@"Hjdaslk"];[_data addObject:@"Hdjskldj"];
      [_data addObject:@""];
      [_data addObject:@"dsalkdmsalkn"];
      [_data addObject:@""];
      [_data addObject:@"jdopecnl"];
      [_data addObject:@"Hassan"];
      [_data addObject:@"sdsdklsmlfmf"];
      [_data addObject:@""];
      [_data addObject:@""];[_data addObject:@"sdnsad"];
      [_data addObject:@"nsadn"];
      [_data addObject:@"dlsadn"];
      [_data addObject:@"sdslakdn"];
   }


 - (UITableViewCell *)tableView:(UITableView *)tableView    cellForRowAtIndexPath:(NSIndexPath *)indexPath {
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
     NSLog(@"%ld",(long)indexPath.row);
     NSLog(@"%@",[_data objectAtIndex:indexPath.row]);
     UITextField * field = (UITextField*)[cell viewWithTag:1000];
     if([[_data objectAtIndex:indexPath.row] length]>0)
     {
         [field setText:[_data objectAtIndex:indexPath.row]];
     } 
   return cell;
 }

当视图第一次运行时,textfields使用数组中的字符串进行初始化,但是当我向下滚动TableView然后上去所有条目搞砸了,数据在文本字段中混洗。 下图是没有滚动enter image description here

的uitableview场景

但是当我向下滚动然后向上滚动我的tableView的条件就像 enter image description here

我还制作了自定义UItableViewCell类并为Textfield创建了iboutlet,但结果是一样的。请建议我最好的解决方案

2 个答案:

答案 0 :(得分:4)

- (UITableViewCell *)tableView:(UITableView *)tableView    cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    NSLog(@"%ld",(long)indexPath.row);
    NSLog(@"%@",[_data objectAtIndex:indexPath.row]);
    UITextField * field = (UITextField*)[cell viewWithTag:1000];
    field.text = @"";
    if([[_data objectAtIndex:indexPath.row] length]>0)
    {
        [field setText:[_data objectAtIndex:indexPath.row]];
    } 
    return cell;
}

您每次都必须重置文本字段文本。

答案 1 :(得分:2)

只是修改为:

if([[_data objectAtIndex:indexPath.row] length]>0)
{
    [field setText:[_data objectAtIndex:indexPath.row]];
} else{
   [field setText:@""];
}

表格视图单元格是可重复使用的,如果每次显示时都不更新它,它只会显示它的内容,“其他”将确保它每次都会更新

相关问题