TableViewCell第一次不显示数据

时间:2015-10-05 09:49:39

标签: ios objective-c uitableview xcode6

UILabels上有两个UITableViewCell

我正在使用故事板,我在自定义单元格中有这些标签,如下所示:

enter image description here

我的cellForRowAtIndex方法:

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

NSLog(@"index = %ld",indexPath.row);  //This logs correct 0,1,2 ..and so on

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
UILabel *lblCellTitle = (UILabel*)[self.view viewWithTag:1];
UILabel *lblCellDetail = (UILabel*)[self.view viewWithTag:2];

lblCellTitle.text = [arrtableDataHeading objectAtIndex:indexPath.row]; //this array contain valid values
lblCellDetail.text = [filterdInfo objectAtIndex:indexPath.row]; //this array contain valid values

return cell;

}

我的问题是,当我第一次打开我的控制器时,数据显示在第二个索引中,最后我看到自定义标签名称,如下所示:

enter image description here

当我滚动时,只会更新数据,并且按随机顺序,我无法按正确的顺序获取数据。

当我调试当indexPath为0时,目标在UILabel中为零,但当它变为1时,我得到正确的值。

enter image description here enter image description here

有人告诉我使用cell.ContentView代替self.view将解决我的问题。但我很困惑这怎么可能。

2 个答案:

答案 0 :(得分:2)

因为我建议您遵循的方式不正确。 根据MVC,如果要制作自定义的东西,您的视图类和控制器类应该是不同的。在您的情况下,您可以创建一个UITableViewCell类,而不是使用其对象来初始化您的单元格。

CommentsTableViewCell *cell = (CommentsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"comments cell"];
    cell.lblName.text = @"String data";
    NSString *dateString = @"String data";
    cell.lblCommentTime.text = @"String data";
    cell.imgDp.image = [UIImage imageNamed: @"String data"];
    cell.lblCommentDuration.text = @"String data";

在上面的代码中,CommentsTableViewCell是UITableViewCell的自定义类。 希望你会发现它有用。

答案 1 :(得分:0)

尝试更改这些行,

UILabel *lblCellTitle = (UILabel*)[self.view viewWithTag:1];
UILabel *lblCellDetail = (UILabel*)[self.view viewWithTag:2];

UILabel *lblCellTitle = (UILabel*)[cell.contentView viewWithTag:1];
UILabel *lblCellDetail = (UILabel*)[cell.contentView viewWithTag:2];

如果它不起作用,请告诉我。