tableView

方式一:解偶的方式创建TableView

#import "TableViewController.h"

#import "TestTableView.h"

@interface TableViewController ()

@property(nonatomic , strong) TestTableView * tableView;

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    [self loadDataisFirst];
}

#pragma mark - 交互

- (void)detailClick:(NSIndexPath *)indexPath
{
    NSLog(@"%ld-----------%ld",(long)indexPath.section,(long)indexPath.row);
}

#pragma mark - 网络

- (void)loadDataisFirst
{
    self.tableView.array = @[@"-1-",@"-2-",@"3-3",@"5-5",@"6-6"];
}

#pragma mark - 懒加载

-(UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[TestTableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = UIColor.grayColor;
        [self.view addSubview:_tableView];
        _tableView.itemClick = ^(NSIndexPath * _Nonnull indexPath) {
            [self detailClick:indexPath];
        };
    }
    return _tableView;
}

TestTableView

@interface TestTableView : UITableView

@property (nonatomic, strong) NSArray *array;

@property (nonatomic, copy) void (^itemClick)(NSIndexPath *indexPath);

@end
#import "TestTableView.h"

#import "TestTableViewCell.h"
#import "TestTableViewHeaderFooterView.h"

@interface TestTableView () <UITableViewDelegate, UITableViewDataSource>

@end

@implementation TestTableView

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        //
        self.delegate = self;
        self.dataSource = self;
        [self registerClass:[TestTableViewCell class] forCellReuseIdentifier:NSStringFromClass(TestTableViewCell.class)];
        [self registerClass:[TestTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass(TestTableViewHeaderFooterView.class)];
    }
    return self;
}

#pragma mark - 交互


#pragma mark - delegate

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

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(TestTableViewCell.class) forIndexPath:indexPath];
    cell.reasonLabel.text = [NSString stringWithFormat:@"我是第%ld个cell",(long)indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.itemClick) {
        self.itemClick(indexPath);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    TestTableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass(TestTableViewHeaderFooterView.class)];
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor =  UIColor.blueColor;
    return footerView;
}

#pragma mark - setter

- (void)setArray:(NSArray *)array
{
    _array = array;
    [self reloadData];
}


方式二:保守的创建方式TableView

estimated:预估

//高度自适应
self.tableView.estimatedRowHeight = 88;
self.tableView.rowHeight = UITableViewAutomaticDimension;
//cell的细节
[self.contentView addSubview:self.retryBtn];

//在iOS 11上运行tableView向下偏移64px或者20px,因为iOS 11废弃了automaticallyAdjustsScrollViewInsets,
//而是给UIScrollView增加了contentInsetAdjustmentBehavior属性。避免这个坑的方法是要判断
if (@available(iOS 11.0, *)) {
_tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
}else {
self.automaticallyAdjustsScrollViewInsets = NO;
}

//tableView的sectionHeader、sectionFooter高度与设置不符,因为tableView的estimatedRowHeight、
//estimatedSectionHeaderHeight、 estimatedSectionFooterHeight三个高度估算属性由默认的0变成了
//UITableViewAutomaticDimension。最简单的方法就是直接设置为0。
_tableView.estimatedSectionHeaderHeight = 0;
_tableView.estimatedSectionFooterHeight = 0;
_tableView.estimatedRowHeight = 0;

TableViewController.h

#import "TableViewController.h"

#import "TestTableViewCell.h"
#import "TestTableViewHeaderFooterView.h"

@interface TableViewController ()<UITableViewDelegate , UITableViewDataSource>

@property(nonatomic , strong) UITableView * tableView;

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.tableView];
}

#pragma mark - UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(TestTableViewCell.class) forIndexPath:indexPath];
    cell.reasonLabel.text = [NSString stringWithFormat:@"我是第%ld个cell",(long)indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    TestTableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass(TestTableViewHeaderFooterView.class)];
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor =  UIColor.blueColor;
    return footerView;
}

#pragma mark - 懒加载

-(UITableView *)tableView
{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStyleGrouped];
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[TestTableViewCell class] forCellReuseIdentifier:NSStringFromClass(TestTableViewCell.class)];
        [_tableView registerClass:[TestTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass(TestTableViewHeaderFooterView.class)];
        _tableView.backgroundColor = UIColor.grayColor;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

@end

TestTableViewCell

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface TestTableViewCell : UITableViewCell

@property(nonatomic,strong)UILabel *reasonLabel;

@end

NS_ASSUME_NONNULL_END
#import "TestTableViewCell.h"

@implementation TestTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
//        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self setUI];
        [self layout];
    }
    return self;
}

- (void)setUI{
    NSLog(@"---");
    [self.contentView addSubview:self.reasonLabel];
}

- (void)layout{
    self.reasonLabel.frame = CGRectMake(0, 0, 300, 100);
}

#pragma mark - 懒加载

- (UILabel *)reasonLabel{
    if (!_reasonLabel) {
        _reasonLabel = [[UILabel alloc]init];
        _reasonLabel.text = @"cell";
    }
    return _reasonLabel;
}

@end

TestTableViewHeaderFooterView

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface TestTableViewHeaderFooterView : UITableViewHeaderFooterView

@property(nonatomic,strong)UILabel *reasonLabel;

@end

NS_ASSUME_NONNULL_END
#import "TestTableViewHeaderFooterView.h"

@implementation TestTableViewHeaderFooterView

- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier {
    
    self = [super initWithReuseIdentifier:reuseIdentifier];
    if (self) {
        [self setUI];
        [self layout];
        self.contentView.backgroundColor = UIColor.redColor;
    }
    return self;
}

- (void)setUI{
    NSLog(@"+++");
    [self.contentView addSubview:self.reasonLabel];
}

- (void)layout{
    self.reasonLabel.frame = CGRectMake(0, 0, 200, 30);
}

#pragma mark - 懒加载

- (UILabel *)reasonLabel{
    if (!_reasonLabel) {
        _reasonLabel = [[UILabel alloc]init];
        _reasonLabel.text = @"TableViewHeaderFooterView";
    }
    return _reasonLabel;
}

@end


用xib加约束和用masonry加代码约束都是的的cell自适应高度的使用方法

加好约束后,然后告诉tableView自己去适应高度就可以了。有两种写法:

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 100;
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

这个的意思就是告诉tableView,你需要自己适应高度,我不给你算啦哈哈哈。但是我们需要告诉它一个大概高度,例如上面的100,理论上这个是可以随便写的,并不影响显示结果,但是越接近真实高度越好。
其实section的header和footer也是可以自动适应的,对应的方法有

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section;
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section;

点击状态栏就有几率不能精确滚动到顶部了(不太算bug的bug)

如果我们用了自动计算高度的方法,又调用了tableView的reloadData方法(例如我们的数据有分页的时候,加载完下一页的数据后会去刷新tableView)。这时候就会出现问题,点击状态栏就有几率不能精确滚动到顶部了。

@property (nonatomic, strong) NSMutableDictionary *heightAtIndexPath;//缓存高度所用字典

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSNumber *height = [self.heightAtIndexPath objectForKey:indexPath];
    if(height)
    {
        return height.floatValue;
    }
    else
    {
        return 100;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSNumber *height = @(cell.frame.size.height);
    [self.heightAtIndexPath setObject:height forKey:indexPath];
}

解释一下,就是用一个字典做容器,在cell将要显示的时候在字典中保存这行cell的高度。然后在调用estimatedHeightForRowAtIndexPath方法时,先去字典查看有没有缓存高度,有就返回,没有就返回一个大概高度。

常规的cell缓存高度

因为当tableView滚动时会不停的回调- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;这个代理方法,当cell的高度需自适应内容时,就意味着每次回调这个方法时都要计算高度,而计算是要花时间了,在用户体验上的体现就是卡顿。为了避免重复且无意义的计算cell高度,缓存高度就显得尤为重要了。

/** 缓存cell高度的数组 */
@property (nonatomic,strong) NSMutableArray *heightArray;

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat height;
    
    if (self.heightArray.count > indexPath.row) {
        // 如果有缓存的高度,取出缓存高度
        height = [self.heightArray[indexPath.row] floatValue];;
    }else{
        // 无缓存高度,计算高度,并加入数组
        
        // 高度根据评论内容多少自适应
        CQGoodsCommentModel *model = self.dataArray[indexPath.row];
        // 列寬
        CGFloat contentWidth = screenWidth-20;
        // 用何種字體進行顯示
        UIFont *font = [UIFont systemFontOfSize:13];
        // 计算size
        CGSize size = [model.comment_content sizeWithFont:font constrainedToSize:CGSizeMake(contentWidth, 1000) lineBreakMode:UILineBreakModeWordWrap];
        
        // 這裏返回需要的高度
        height = size.height+60;
        // 加入数组
        [self.heightArray addObject:[NSNumber numberWithDouble:height]];
    }
    return height;
}

下拉刷新tableView时记得清空高度缓存数组。
最好的方案:放在model里,拿到数据的时候就提前计算了



tableView数据处理方案

- (void)loadData
{
    self.searchPage = 1;
    [self loadDataGoods:self.searchPage first:YES];
}

- (void)loadDataRefresh
{
    self.searchPage = 1;
    [self loadDataGoods:self.searchPage first:NO];
}

- (void)loadDataMore
{
    self.searchPage++;
    [self loadDataGoods:self.searchPage first:NO];
}

//成功
if (listArray.count < kPageSize) {
    dispatch_async(dispatch_get_main_queue(), ^(){
        [weakSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
    });
}
if (weakSelf.searchPage == 1)
{
    [weakSelf.modeArray removeAllObjects];
    (listArray.count == 0) ? (weakSelf.notDataView.hidden = NO) : (weakSelf.notDataView.hidden = YES);
}
else if (weakSelf.searchPage > 1 && listArray.count == 0)
{
    weakSelf.searchPage--;
}

//失败
weakSelf.searchPage--;
if (weakSelf.modeArray.count > 0) {
    //处理:吐司
    return;
}
 //处理:第一次加载,网络不给力(重试),加载失败(重试),吐司,(mj_footer,mj_header,hidden = YES)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,393评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,790评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,391评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,703评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,613评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,003评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,507评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,158评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,300评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,256评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,274评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,984评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,569评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,662评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,899评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,268评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,840评论 2 339

推荐阅读更多精彩内容