我有一个包含四个部分的表格视图,所有部分都有两个文本字段和一个位于不同行的标签。我添加了一些文本作为文本字段的占位符。最初,数据看起来很好,但是当我滚动表格视图时,单元格开始出现重叠的数据。
My Code:
- (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;
}
提前致谢
Pankaj
您只需在初始化单元格的代码块中创建文本字段。请记住,表视图会回收单元格,因此当您滚动屏幕时,您会得到一个已具有文本字段的重复使用和回收的单元格。然后,您将创建一个新的文本字段并将新的文本字段覆盖在现有的文本字段上,因此会出现重叠。
这是您正确重构的代码
- (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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)