静态TableVIew的使用

前言

有些UI上的cell无需复用,可以用此方法。

正文

  • 首先写一个protocol,给我们接下来会用到的自定义cell。
@protocol TCStaticTableViewCellProperty <NSObject>

@optional
@property (nonatomic, assign) CGFloat height;

@end
  • 给ViewController定义一个属性。
@property (nonatomic, strong) NSMutableArray <UITableViewCell<TCStaticTableViewCellProperty>*>*cells;
  • 遵守协议
#pragma mark - UITableViewDataSource - Method

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cells.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.cells[indexPath.row];
}

#pragma mark - UITableViewDelegate - Method
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.cells[indexPath.row].height;
}
  • 然后self.cells的cell需要自定义且遵守协议< TCStaticTableViewCellProperty >。
@interface HomeBaseCell : UITableViewCell <TCStaticTableViewCellProperty>
@property (nonatomic, assign) CGFloat height;
@end
  • 以下是初始化一个44高度的cell的例子,可以是xib生成的cell也可以是直接代码构建的。
@implementation HomeBaseCell

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        self.height = 44;
    }
    return self;
}

- (instancetype)init {
    if (self = [super init]) {
        self.height = 44;
    }
    return self;
}
@end
  • 当然也可以直接不需要height属性,直接重写protocol的getter方法。
- (CGFloat)height {
    return 44;
}
  • 直接重写protocol的getter方法,那样不能更改cell的高度,有些虽然是同一个cell,但是不同的场景可能高度不同,那样就不好用了。

先写到这。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容