静态TableVIew的使用

前言

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

正文

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

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

@end
  • 给ViewController定义一个属性。
@property (nonatomic, strong) NSMutableArray *>*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 
@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,但是不同的场景可能高度不同,那样就不好用了。

先写到这。

你可能感兴趣的:(静态TableVIew的使用)