且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UITableViewCell 中的 UITextField - 防止文本重置的方法

更新时间:2023-01-12 16:06:55

当您在 cellForRowAtIndexPath 中创建单元格时,您必须为第一个单元格使用一个可重用标识符(即 cellId1),另一个用于其余的(即 cellId2).

When you are creating cells in cellForRowAtIndexPath you have to use one reusable identifier for that first cell (ie. cellId1) and another for the rest (ie. cellId2).

如果这样做,当您通过调用 [tableView dequeueReusableCellWithIdentifier:@"cellId1"] 获取第一个元素的单元格时,您将始终获得相同的对象,并且不会被其他单元格重复使用.

If you do this, when you get the cell for the first element by calling [tableView dequeueReusableCellWithIdentifier:@"cellId1"] you will always get the same Object and will not be reused by other cells.

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

    MyCell *cell = nil;

    // Only for first row
    if (indexPath.row == 0) {
        static NSString *cellId1 = @"cellId1";
        cell = [tableView dequeueReusableCellWithIdentifier:cellId1];

        if (cell == nil) {
            cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId1];
        }
    }
    else {
        static NSString *cellId2 = @"cellId2";
        cell = [tableView cellId2];

        if (cell == nil) {
            cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault cellId2];
        }
    }

    // do whatever

    return cell;
}