美文网首页
静态TableVIew的使用

静态TableVIew的使用

作者: 范德萨范德萨范德萨 | 来源:发表于2017-11-29 11:27 被阅读7次

前言

有些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,但是不同的场景可能高度不同,那样就不好用了。

先写到这。

相关文章

网友评论

      本文标题:静态TableVIew的使用

      本文链接:https://www.haomeiwen.com/subject/xddubxtx.html