OC-UITableView快速注册获取Cell

Swift版

前言
Swift开发久了突然回归,发现工具类少了点,今天特意写了一点,UITableView是常用的列表控件,但是用系统的注册方法比较麻烦,需要根据xib与class来分别注册,比较麻烦,下文是对UITableView进行扩展

注册原理:
1.首先通过传入- (void)hw_registerCell:(id)cell方法中的cell通过筛选过滤出cell名称
2.通过cell名称,判断xib是否存在
3.xib存在即时nib注册方式,反正为class

获取cell原理:
1.通过[self dequeueReusableCellWithIdentifier:reuseIdentifier];去缓存池中,获取对象是否存在,如果存在说明已经注册,如果没有说明没有注册
2.通过上面结果,如果没有注册,调用注册方法,再调用系统的[self dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];返回,反之直接返回

image.png

使用案例

// 注册cell
[self.tableView hw_registerCell:@"UITableViewCell"];

// 获取cell (可以通过Class和字符串 推荐用class)
textCell *cell = [tableView hw_dequeueReusableCell:[textCell class] and:indexPath];
textCell *cell = [tableView hw_dequeueReusableCell:@"textCell" and:indexPath];

原理给UITableView添加类别
.h文件

#import 

NS_ASSUME_NONNULL_BEGIN
@interface UITableViewCell (HWCategory)

/**
 快速获取注册cellid
 @return 注册的类名+ID
 */
+ (NSString *)hw_identifier;
@end


@interface UITableView (HWCategory)
/**
 快速注册cell 根据传入的cellName自动判断是注册的xib还是Class
 @param cell cell的class 或者cell字符串
 */
- (void)hw_registerCell:(id)cell;

/**
 快速获取cell 可以不用注册 内部自动判断是否注册 未注册自动注册
 
 @param cell cell的class 或者cell字符串 (推荐用class类型)
 @param indexPath 对应的NSIndexPath
 @return cell
 */
- (id)hw_dequeueReusableCell:(id)cell and:(NSIndexPath *)indexPath;
@end

NS_ASSUME_NONNULL_END

.m文件

#import "UITableView+HWCategory.h"

@implementation UITableViewCell (HWCategory)
+ (NSString *)hw_identifier {
    return [NSString stringWithFormat:@"%@ID",NSStringFromClass([self class])];
}
@end

@implementation UITableView (HWCategory)
- (void)hw_registerCell:(id)cell {
    NSString *cellName = [self getCellName:cell];
    NSString *reuseIdentifier = [NSString stringWithFormat:@"%@ID", cellName];
    if ([self hw_getNibPath:cellName]) {
        [self registerNib:[UINib nibWithNibName:cellName bundle:nil] forCellReuseIdentifier:reuseIdentifier];
    } else {
        [self registerClass:NSClassFromString(cellName) forCellReuseIdentifier:reuseIdentifier];
    }
}

- (id)hw_dequeueReusableCell:(id)cell and:(NSIndexPath *)indexPath {
    NSString *cellName = [self getCellName:cell];
    NSString *reuseIdentifier = (NSString *)[NSString stringWithFormat:@"%@ID", cellName];
    UITableViewCell *newCell = [self dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (newCell == nil) {
        [self hw_registerCell:cell];
    }
    return [self dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
}
- (NSString *)getCellName:(id)cell {
    NSString *cellName;
    if ([cell isKindOfClass:[NSString class]]) {
        cellName = cell;
    } else {
        cellName = NSStringFromClass(cell);
    }
    return  cellName;
}
// 通过判断nib是否存在来确认注册方式
- (BOOL)hw_getNibPath:(NSString *)name {
    NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"nib"];
    if (path == nil) { // 路径不存在
        return NO;
    } else { // 路径存在
        return YES;
    }
}
@end

你可能感兴趣的:(OC-UITableView快速注册获取Cell)