1

我正在研究一个tableview,我是动态创建单元格的新手(我曾经用IB创建它们,然后将它们链接到它们的tableviewcell控制器等......)。

一切正常,recepted 数组已正确更新,但是当我触发 [self.tableview reloadData] 时,程序只是在旧单元格上重绘新值。例如,如果单元格内的 uilabel 中有“TEST CELL”值,当我将数据更新为“CELL TEST”并触发 reloadData 时,uilabel 看起来就像有两个标签在彼此之上并且两个值都是可见的。(就像创建两个具有完全相同位置和相同大小的 uilabel 并设置它们的值)

每次我触发 reloadData 时都会发生此事件,每次重新加载时,程序看起来就像在旧的 uilabel 之上添加了另一个 uilabel。这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
UILabel *lblText1 = [[UILabel alloc] initWithFrame:CGRectMake(30, 5, 130, 30)];
lblText1.adjustsFontSizeToFitWidth = YES;
lblText1.backgroundColor = [UIColor clearColor];
lblText1.text = [lblText1Array objectAtIndex:indexPath.row];
[cell addSubview:lblText1];
[lblText1 release];
if(indexPath.row<3)
{   
    UILabel *lblText2 = [[UILabel alloc] initWithFrame:CGRectMake(170, 5, 130, 30)];
    lblText2.adjustsFontSizeToFitWidth = YES;
    lblText2.backgroundColor = [UIColor clearColor];
    lblText2.text = nil;
    lblText2.text = [spParameters objectAtIndex:indexPath.row];
    [cell addSubview:lblText2];
    [lblText2 release];
}
else if(indexPath.row==3){
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(170, 7, 130, 30)];
    textField.adjustsFontSizeToFitWidth = YES;
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.placeholder = @"please insert value";
    textField.textAlignment = UITextAlignmentCenter;
    textField.delegate = self;
    textField.text = [spParameters objectAtIndex:indexPath.row];
    [cell addSubview:textField];
    [textField release];
}
else if(indexPath.row == 4)
{
    UISwitch *gSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(170, 7, 130, 30)];
    [gSwitch setOn:FALSE];
    [gSwitch addTarget: self action: @selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
    [cell addSubview:gSwitch];
    [gSwitch release];
}
// Configure the cell...
return cell;

}

我在将组件添加到子视图后释放了这些组件,我正在考虑重用标识符是否有问题......

感谢您的帮助。

4

1 回答 1

1

看起来好像您正在使用固定数量的单元格填充详细视图,因此您应该考虑静态创建实例,例如在 Interface Builder 中viewDidLoad或在 Interface Builder 中。您可以将每个单元格存储在一个单独的实例变量中,并且每次tableView:cellForRowAtIndexPath:调用时只返回与当前行对应的那个。

如果您以编程方式创建单元格,请添加您当时需要的任何子视图。否则,正如我所提到的,您可以在 Interface Builder 中执行此操作,这通常可以更轻松地设置控件的详细信息,例如文本字段。请注意,虽然它UITableViewCell已经包含 的实例UILabel,所以自己添加一个是多余的。相反,只需访问单元格的textLabel属性即可获取其标签。

于 2011-02-08T16:41:45.387 回答