IOS面试题(TableView) ----- 重用机制

2022-03-28  本文已影响0人  ShawnAlex

问题: 请说一下tableview的重用机制

先看个例子

- (UITableView *)tableView {
    
    if (!_tableView) {

        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT - kStatusBarAndNavigationBarHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[XXXTableViewCell class] forCellReuseIdentifier:@"XXXCellId"];
    }
    
    return _tableView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    XXXTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XXXCellId"]
    cell.delegate = self;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    return cell;
}

这里是tableview通常写法, 而其中dequeueReusableCellWithIdentifier:, 通过指定一个标识符来获取一个cell, 就使用到了tableview重用机制

例子

如图, UITableView正在向上滑动, 其中

因为都是用的同一标识符(id), Cell-6就可以复用Cell-0开辟的内存, 从而达到复用的目的, 其实这就是TableView的重用机制。

上一篇 下一篇

猜你喜欢

热点阅读