ios - UItableView Cell Resuablity 数据在滚动时被交换

标签 ios iphone uitableview reuseidentifier

Grouped TableView with 4 rows in each Section

大家好,

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

        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 5, 200, 30)];
        textField.tag = 123;
        textField.placeholder = @"Enter Text";
        textField.autocorrectionType = UITextAutocorrectionTypeNo;
        textField.delegate = self;
        [cell.contentView addSubview:textField];

    }

    UITextField *textField = (UITextField *) [cell.contentView viewWithTag:123];
        if (indexPath.row == 0) {
            [textField setPlaceholder:@"Employee ID"];
        }
        else if (indexPath.row == 1)
        {
            [textField setPlaceholder:@"Employee Name"];
        }
        else if (indexPath.row == 2)
        {
            [textField setPlaceholder:@"Employee Phone"];
        }
         if (indexPath.row == 3)
        {
            [textField setPlaceholder:@"Employee Email"];
            UIButton *saveButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
            [saveButton setFrame:CGRectMake(200, 0, 100, 40)];
            [saveButton setTitle:@"Save Emp" forState:UIControlStateNormal];
            [saveButton addTarget:self action:@selector(saveEmployeeToCoreData:) forControlEvents:UIControlEventTouchUpInside];
            [saveButton setTag:indexPath.section];
            [cell addSubview:saveButton];
        }

    return cell;
}

大家好, 我正在使用这段代码来获得上面的输出 但是当我滚动表格 View 时,我得到的输出是

when i am scrolling the tableview the output i am getting

如果我在该部分中输入任何文本并滚动文本,那么单元格中的文本就会发生变化。

最佳答案

在其中一种情况下,您正在向单元格添加 subview :

[cell addSubview:saveButton];

当您将旧单元格出列时,此 subview 不会被删除。对于这些情况,您必须明确删除 subview 。这将导致意外行为。

我真的建议继承 UITableViewCell 并将组件添加到该子类。通过这样做,您可以在不需要保存按钮的情况下隐藏其保存按钮属性。

关于ios - UItableView Cell Resuablity 数据在滚动时被交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21303936/

相关文章:

uitableview - 将按日期分隔的部分添加到 Swift CoreData 中的 UITableView

ios - UITableView 行分隔符问题

ios - 如何在 swift 3 的 UITableView 中创建和使用变量

iphone - 如何将 "filters"应用于 AVCaptureVideoPreviewLayer

ios - PhoneGap 构建 iOS 钥匙串(keychain)访问?

iOS : Switching between 12/24 hour times from strings

ios - 如何在 UICollectionView 之后添加额外的可见空间

iphone - NSManagedObject 到 JSON

iphone - 如何让输入标签在 iPhone/iPad 上正确显示?

ios - 在 Web 服务调用响应中自动填充文本