OC、Swift Cell Identifier改造

Swift Cell 改造

参考:https://gist.github.com/gonzalezreal/92507b53d2b1e267d49a

  • 我们定义一个协议 Reusable , 含有一个静态变量 identifier.
  • 然后利用 extension UIView 泛型, 实现一个默认方法,返回让 identifier 与类型相同
  • 这里我的 UIViewController 也实现了这个协议,这个前提是 Storyboard 中设置的 Storyboard ID 与类名相同, 否则会 crash
/// 可复用协议
protocol Reusable: class {
  /// 复用的id
  static var identifier: String { get }
}

extension Reusable where Self: UIView {
  static var identifier: String {
    return NSStringFromClass(self)
  }
}

extension UICollectionViewCell: Reusable {}

extension UITableViewCell: Reusable {}

// 这个前提是 Storyboard 中设置的 Storyboard ID 与类名相同, 否则会 crash
extension UIViewController: Reusable {
  static var identifier: String {
    let className = NSStringFromClass(self) as NSString
    return className.components(separatedBy: ".").last!
  }
}

// 调用时,就可以这么调用了
let cell = tableView.dequeueReusableCell(withIdentifier: CustomerCell.identifier)

OC Cell 改造

  • 因为先弄了 swift,然后我又想着把 OC 的代码也改掉,最开始我想用 Category 实现,做 identifier 肯定是没问题的,但是我发现我还可以再多抽取一点重复的代码到基类中。于是我写了个 BaseCell,结果就成了下面这样。
  • 继承 SCBaseTableViewCell 然后就不用再写 cellWithTableViewinitWithStyle
@implementation SCBaseTableViewCell

+ (instancetype)cellWithTableView:(UITableView *)tableView {
    NSString *identifier = NSStringFromClass(self);
    SCBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[self alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setupViews];
    }
    return self;
}

// 由子类去实现视图自定义
- (void)setupViews {}

@end

// 方法调用
SCActivityCell *cell = [SCActivityCell cellWithTableView:tableView];
cell.model = model;

你可能感兴趣的:(OC、Swift Cell Identifier改造)