滚动时UITableViewCells不会被重用

时间:2014-02-01 05:17:10

标签: ios iphone objective-c uitableview

我正在构建一个应用程序,其中屏幕应该显示一个tableview,在tableview中,前两行是两个不同的自定义单元格,其余的是不同的自定义单元格。所以我在我的cellForRowAtIndexPath中做了这个: 我的代码:

if (indexPath.row == 0 && !isSearchEnabled) {
         FirstRowViewCell *cell;
        static NSString *CellIdentifier = @"FirstCell";

       cell =  [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {

            // load a new cell from the nib file
            [[NSBundle mainBundle] loadNibNamed:@"ContactCell" owner:self options:nil];
            cell = self.firstCell;
            //cell.delegate = self;
            //cell.indexPath = indexPath;
            self.firstCell = nil;

        }
        return cell;
    } else if (indexPath.row == 1 && !isSearchEnabled) {
        SecondRowViewCell *cell;
        static NSString *CellIdentifier = @"SecondCell";

        cell =  [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {

            // load a new cell from the nib file
            [[NSBundle mainBundle] loadNibNamed:@"ContactCell" owner:self options:nil];
            cell = self.secondCell;
            //cell.delegate = self;
            //cell.indexPath = indexPath;
            self.secondCell = nil;

        }
        return cell;
    }else {

    static NSString *CellIdentifier = @"ContactCell";

    ContactTableCell *cell =  [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {


          [[NSBundle mainBundle] loadNibNamed:@"ContactCell" owner:self options:nil];

        // load a new cell from the nib file

        cell = self.contactCell;
        cell.delegate = self;
        cell.indexPath = indexPath;
        self.contactCell = nil;

    }
    return cell;}

但滚动tableview时滞后。当我用仪器中的Time Profiler检查时,它显示了cellForRowAtIndexPath尤其是

[[NSBundle mainBundle] loadNibNamed:@"ContactCell" owner:self options:nil];

需要花费很多时间来加载导致滞后的问题。我的问题是,单元格是否被重用,因为即使我们滚动到顶部,上面的行也会为每个单元格执行。请帮我解决滞后问题。谢谢!

2 个答案:

答案 0 :(得分:4)

尝试这可能会有所帮助

 static NSString *simpleTableIdentifier = @"ContactCell";

ContactCell *cell = (ContactCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ContactCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];


}         

return cell;

答案 1 :(得分:3)

您正在创建没有设置reuseIdentifier的单元格。 reuseIdentifierUITableViewCell的只读属性。您应该做的是使用tableview注册nib,可能是viewDidLoad的{​​{1}}或viewWillAppear方法。

UIViewController

执行此操作后,UINib *cellNib = [UINib nibWithNibName:@"ContactCell" bundle:nil]; [tableView registerNib:nib forCellReuseIdentifier:CellIdentifier]; 将始终返回一个有效的单元格,无论是实例化还是重复使用它。

您可以参考此Apple文档:UITableViewUITableViewCellUINib

相关问题