https://github.com/dreamengine/DETableViewCell
DETableViewCell 是一个 MIT 许可的 UITableViewCell 替换,使得单元格管理变得简单。它负责为每个 DETableViewCell 子类创建和维护 UINibs,使得 UINibs 能够在多个控制器之间重用,无需担心。
在创建自定义单元格时,从 DETableViewCell 而不是 UITableViewCell 继承。由于 DETableViewCell 本身就是 UITableViewCell 的子类,因此改变您的自定义单元格的上层类不会丢失任何内容。
@interface MyCustomCell : DETableViewCell
...
@end
@implementation MyCustomCell
...
@end
要访问单元格类的 UINib,只需在该类上使用 +cellNib。如果已为该类创建了 UINib 实例,则此方法将直接返回该对象。否则,此方法将自动为该类创建新的 UINib,存储在 DETableViewCell 缓存中,并返回该对象。nib 实例化过程要求 .xib/.nib 文件与 DETableViewCell 子类的名称相同。
#import "MyCustomCell.h"
#import "OtherCustomCell.h"
@implementation SomeObject
-(void)someMethod {
UINib *myNib = [MyCustomCell cellNib]; // returns a UINib loaded with "MyCustomCell.nib"
UINib *otherNib = [OtherCustomCell cellNib]; // returns a UINib loaded with "OtherCustomCell.nib"
}
@end
如果需要手动创建单元格实例,只需在您的 DETableViewCell 子类上使用 +cell 即可,这将利用 UINib 缓存系统从对应的 nib 文件中膨胀。
-(void)someMethod {
MyCustomCell *customCell = [MyCustomCell cell];
}
为了进一步简化应用程序中表格单元格的使用,DETableViewCell 提供了使用 NSStringFromClass() 的默认重用标识符。无论是 +reuseIdentifier 还是对 -reuseIdentifier,它们都返回相同的字符串,这使得在注册 nib 和从 UITableViews 中排空单元格都更容易。
#import "MyCustomCell.h"
#import "OtherCustomCell.h"
@implementation SomeController
-(void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerNib:MyCustomCell.cellNib forCellReuseIdentifier:MyCustomCell.reuseIdentifier];
[self.tableView registerNib:OtherCustomCell.cellNib forCellReuseIdentifier:OtherCustomCell.reuseIdentifier];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.section == 0) {
MyCustomCell *customCell = [self.tableView dequeueReusableCellWithIdentifier:MyCustomCell.reuseIdentifier forIndexPath:indexPath];
return customCell;
}
else {
OtherCustomCell *otherCell = [self.tableView dequeueReusableCellWithIdentifier:OtherCustomCell.reuseIdentifier forIndexPath:indexPath];
return otherCell;
}
}
还提供了一个 UITableView 分类来简化重用注册。不用使用 -registerNib:forCellReuseIdentifier:,只需使用 -registerDETableViewCellClass:。
-(void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerDETableViewCellClass:MyCustomCell.class];
[self.tableView registerDETableViewCellClass:OtherCustomCell.class];
}
DETableViewCell 使用了一个自定义的 NSCache 对象,这个对象也会对低内存警告做出响应。当内存限制增加时,缓存将自动驱逐项目,这意味着你不必担心 DETableViewCell 的缓存策略。
但是,可能有时你需要手动删除缓存 UINib 以在选择内存限制发生之前从内存中移除。要这样做,请在相应的类上调用 +removeCellNibFromCache。
也可能存在一些情况,在这种情况下,手动清除整个 UINib 缓存是合理的。要这样做,请在任何 DETableViewCell 类上调用 +removeAllCellNibsFromCache。
-(void)someMethod {
[MyCustomCell removeCellNibFromCache]; // remove MyCustomCell's UINib from the cache
[DETableViewCell removeAllCellNibsFromCache]; // remove all UINibs from the cache
}