UITableView通过加载xib文件注册Cell的两种方法 - Apple Developer

2022年3月31日 1427点热度 0人点赞 0条评论

UITableView通过加载xib文件注册Cell的两种方法 - Apple Developer

本次加载方式的展示分为Objective-C与Swift方式,两种的使用方式都是差不多的;如果有不对的地方还信指正。

Objective-C中通过xib文件注册Cell的两种方法

1.如使用第一种方法进行xib Cell的注册,需要在xib的配置文件设置identifier与代码中的一致,否则每次都会创建新的

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OCTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"OCTableViewCell"];
    if (!cell) {
        cell =  [[NSBundle mainBundle]loadNibNamed:@"OCTableViewCell" owner:self options:nil].firstObject;
    }
    cell.model = storeArr[indexPath.row];
    return cell;
}

 

2. 如使用第二种方法进行registerNib配置,即可实现cell重用;无需在xib配置页面中设置identifier

⚠️:如果在xib配置页面设置了identifier,则必须与代码中的identifier保持一致性,不然使用过程会崩溃。提示:(reason: 'cell reuse indentifier in nib (OCTableViewCell1) does not match the identifier used to register the nib (OCTableViewCell1)')

 

// 注册 Cell
[self.tableView registerNib:[UINib nibWithNibName:@"OCTableViewCell" bundle:nil] forCellReuseIdentifier:@"OCTableViewCell"];


// Cell 实现
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OCTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"OCTableViewCell"];
    cell.model = storeArr[indexPath.row];
    return cell;
}

 

 

Swift中通过xib文件注册Cell的两种方法

这里只是把Objective-C中的方法转为Swift中的

1.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCell(withIdentifier:"SwiftWorkTableViewCell") as? SwiftWorkTableViewCell
    if cell == nil {
        cell = Bundle.main.loadNibNamed("SwiftWorkTableViewCell", owner: self, options: nil)?.first as? SwiftWorkTableViewCell
    }
    
    cell?.model = storeArr[indexPath.row]
                
    return cell!
}

 

2.

tableView.register(UINib(nibName: "SwiftTableViewCell", bundle: nil), forCellReuseIdentifier: "SwiftTableViewCell")


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    var cell = tableView.dequeueReusableCell(withIdentifier: "SwiftTableViewCell")
    cell?.model = storeArr[indexPath.row];
    return cell!;
}

 

 

 

先这么多,后续在添加

帮助教程

提供最新的帮助教程,方便使用。

文章评论