【问题标题】:UiTextField creating mess with data when using in UitableView.UiTextField 在 UtableView 中使用时会造成数据混乱。
【发布时间】:2016-06-08 15:31:01
【问题描述】:

我创建了一个只有一个 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;
 }

当视图第一次运行时,文本字段会使用数组中的字符串进行初始化,但是当我向下滚动 TableView 然后向上滚动时,所有条目都搞砸了,数据在文本字段中随机排列。 下图是不滚动的uitableview场景

但是当我向下滚动然后向上滚动时,我的 tableView 的情况就像

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

【问题讨论】:

    标签: ios uitableview


    【解决方案1】:
    - (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;
    }
    

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

    【讨论】:

      【解决方案2】:

      只是为了修改这个:

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

      表格视图单元格是可重复使用的,如果您不每次显示时都更新它,它只会显示原来的内容,'else' 将确保它每次都会更新

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多