uitableviewcell的数据在滚动时相互重叠

pan*_*kaj 2 iphone uitableview

我有一个包含四个部分的tableview,所有部分都有两个文本字段和一个不同行的标签.我添加了一些文本作为textfield的占位符.最初数据看起来很好,但是当我滚动tableview时,单元格开始重叠数据.
我的代码:

- (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];
}
if(indexPath.row==0) {
    UITextField *txtName = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 300, 30)];
    txtName.placeholder = @"Full Name";
    [cell.contentView addSubview:txtName];
    [txtName release];
}
else if(indexPath.row==1) {
    UITextField *txtEmail = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 300, 30)];
    txtEmail.placeholder = @"Email";
    [cell.contentView addSubview:txtEmail];
    [txtEmail release];
}
else if(indexPath.row==2){
    cell.textLabel.text = @"Select Date of Birth";
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell...

return cell;
Run Code Online (Sandbox Code Playgroud)

}

在此先感谢
Pankaj

Jas*_*gun 17

您只需要在单元格中的代码块中创建文本字段.请记住,表视图会循环使用单元格,因此当您滚动屏幕时,您将获得一个已经具有文本字段的重用和已回收单元格.然后,您将创建一个新的文本字段并将新文本字段覆盖在现有文本字段上,因此您将重叠.

这是你的代码正确重构

- (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];

        //create the textField here, and we will reuse it and reset its data for each row.
        UITextField *txtField = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 300, 30)];
        [cell.contentView addSubview:txtField];
        txtField.tag=110; //should declare a constant that uniquely defines your textField;
        [txtField release];

    }

    // Configure the cell...

    //ok, now we retrieve the textField and set its data according to the row.
    UITextField *txtField = (UITextField *)[cell.contentView viewWithTag:110];

    if(indexPath.row==0) {
        txtField.placeholder = @"Full Name";   
    }
    else if(indexPath.row==1) {
        txtField.placeholder = @"Email";    
    }
    else if(indexPath.row==2){
        txtField.placeholder = nil;  //? did you mean to set something here?
        cell.textLabel.text = @"Select Date of Birth";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }


    return cell;
}
Run Code Online (Sandbox Code Playgroud)