博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS之tableView(四)自定义cell/注册cell的三种方式/设置预估高度、cell上图文混排实例
阅读量:4289 次
发布时间:2019-05-27

本文共 20898 字,大约阅读时间需要 69 分钟。

  

//当自定义cell,并且没有和xib关联时,调用下面这个方法初始化-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{    if(self=[superinitWithStyle:stylereuseIdentifier:reuseIdentifier]){    }    returnself;}#pragma mark -#pragma mark -  只要一个类和xib进行关联,初始化就是这个方法- (void)awakeFromNib {    }

+++++++++++++++++++++++

 1.  使用自定义cell或者系统的cell,并没有和  xib进行关联      [self.tableView registerClass:[UITableviewCell class] forCellReuseIdentifier:@"QQCell"];    2. 是针对于使用 xib 和自定义cell关联的时候使用UINib *nib = [UINib nibWithNibName:@"QQCell" bundle:nil];[self.tableView registerNib:nib forCellReuseIdentifier:@"QQCell"];   通过注册cell之后,在返回cell的时候,可以省略掉为nil判断   3.在xib或者storyboard中设置了cell的重用标示符 ,不用注册. 

       

 

=============

设置估算高度其实问题出现在这里:- (void)setMessage:(Message *)message {    _message = message;    self.contentLabel.text = _message.content;    self.contentImageView.image = [UIImage imageNamed:_message.imageName];    self.message.cellHeight = CGRectGetMaxY(self.contentImageView.frame) + 10;}我们在得到cellHeight的时候,直接是取imageView的底部+10作为行高,但是在这句之前,label和imageView刚刚拿到数据,还没开始布局,所以我们要在获取cellHeight之前调用layoutIfNeeded方法把他们强制布局一下.升级后的代码:- (void)setMessage:(Message *)message {    _message = message;    // 有的模型不存在文字,这里判断一下    if (_message.content.length) {        self.contentLabel.text = _message.content;    }    else {        self.contentLabel.text =nil;    }        // 有的模型不存在图片,这里进行一下判断    if (_message.imageName.length) {        self.contentImageView.image = [UIImage imageNamed:_message.imageName];    }    else {        self.contentImageView.image =nil;    }    // 强制布局    [self layoutIfNeeded];    self.message.cellHeight = CGRectGetMaxY(self.contentImageView.frame) + 10;}1.优点1> 减少heightForRowAtIndexPath方法的调用次数2> 可以让暂时看不见的cell的高度延迟计算2.缺点1> contentSize的不太准确的2> 滑动过程中,滚动条的长度会变来变去(可能会有跳跃效果)heightForRowAtIndexPath方法的调用时刻     tableView 加载的时候,会先调用这个方法,数据有多少个就调用多少次     每一次调用 cellForRowAtIndexPath:会再一次调用 heightForRowAtIndexPath一.如果没有设置估算高度estimatedRowHeight1.每当reloadData时,有多少条数据,就会调用多少次这个方法;2.每当有cell出现时,也会调用一次这个方法================有预估行高的执行顺序,iOS7如果每个cell高度确实不一样,数据量又很大时该怎么解决这个性能问题呢,iOS7之后系统提供了估算高度的办法,estimatedRowHeight和- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath//下文再提到该方法用estimateHeightForRow代替,这样每次在加载数据之前,tableView不再通过heightForRow消耗大量的性能获取空间大小了,而是通过在estimateRowHeight或者estimatedHeightForRow不需要费劲计算就能获取的一个估算值来获取一个大体的空间大小,等到真正的加载数据时才根据获取真实数据,并做出相应的调整,比如contentSize或者scrollIndicator的位置。- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPathNS_AVAILABLE_IOS(7_0);- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;

 

================ios8没有预估行高的执行顺序

 

 

调用过程大体是这样的:tableView会先询问代理(在一般MVC里大部分是当前视图控制器ViewController)要展示多少个section,就是调用numberOfSections,如果代理没有实现该方法默认就是1个section。然后tableView调用numberOfRowsInSection先询问第一个section有多少个cell,然后挨个执行heightForRow获取每个cell的高度。tableView对每个section都执行一遍这样的操作后,那么结果来了:tableView通过对这些cell高度的累加就知道了需要多大的空间才能安放得了所有的内容,于是它调整好了contentSize的值。这样走下来就为我们后续在滑动时能通过scrollIndicator观察到我们大体滑到了哪个位置做好了准备。

准备好空间之后接下来的任务就是准备内容了。当然大家都知道真正的内容是依附在UITableViewCell上的,tableView先调用cellForRow去获取代理返回给它的第一个cell,对于所有的cell来说width都是固定的,即tableView本身的宽度,对于第一个cell来说它的origin也是确定的,即(0,0),也就是说要想确定这个cell的位置就只需要知道它的height了。于是tableView再去调用heightForRow去获取它的高度,这样一个视图能确定显示在屏幕什么位置的充要条件就具备了。剩下的cell同理,挨个放在上一个cell的下边就行了。

总结一下:

举例:一个组一个cell---------调用顺序

 

 -----------------------------------------------组

2017-05-05 09:22:38.774 ShopMobile[1072:271445]

2017-05-05 09:22:38.774 ShopMobile[1072:271445] cell的高度

2017-05-05 09:22:38.774 ShopMobile[1072:271445] cell.height-0.000000-

2017-05-05 09:22:38.774 ShopMobile[1072:271445]

2017-05-05 09:22:38.774 ShopMobile[1072:271445]

2017-05-05 09:22:38.774 ShopMobile[1072:271445] cell的高度

2017-05-05 09:22:38.775 ShopMobile[1072:271445] cell.height-0.000000-

2017-05-05 09:22:38.778 ShopMobile[1072:271445]

2017-05-05 09:22:38.778 ShopMobile[1072:271445]

2017-05-05 09:22:38.778 ShopMobile[1072:271445]

2017-05-05 09:22:38.778 ShopMobile[1072:271445] cell的高度

2017-05-05 09:22:38.778 ShopMobile[1072:271445] cell.height-0.000000-

2017-05-05 09:22:38.779 ShopMobile[1072:271445]

2017-05-05 09:22:38.780 ShopMobile[1072:271445]

2017-05-05 09:22:38.780 ShopMobile[1072:271445] cell的高度

2017-05-05 09:22:38.780 ShopMobile[1072:271445] cell.height-0.000000-

2017-05-05 09:22:38.789 ShopMobile[1072:271445] -maxH--524.000000

2017-05-05 09:22:38.789 ShopMobile[1072:271445] cell

2017-05-05 09:22:38.790 ShopMobile[1072:271445] cell的高度

2017-05-05 09:22:38.790 ShopMobile[1072:271445] cell.height-525.000000-

  •  

==========有预估行高,iOS8以后

举例:一组,一行cell的调用顺序

 

2017-05-05 09:30:19.741 ShopMobile[1109:322396]

2017-05-05 09:30:19.741 ShopMobile[1109:322396]

2017-05-05 09:30:19.741 ShopMobile[1109:322396]

2017-05-05 09:30:19.741 ShopMobile[1109:322396]

2017-05-05 09:30:19.745 ShopMobile[1109:322396]

2017-05-05 09:30:19.745 ShopMobile[1109:322396]

2017-05-05 09:30:19.745 ShopMobile[1109:322396]

2017-05-05 09:30:19.746 ShopMobile[1109:322396]

2017-05-05 09:30:19.747 ShopMobile[1109:322396]

2017-05-05 09:30:19.756 ShopMobile[1109:322396] -maxH--524.000000

2017-05-05 09:30:19.757 ShopMobile[1109:322396] cell

2017-05-05 09:30:19.757 ShopMobile[1109:322396] cell的高度

2017-05-05 09:30:19.758 ShopMobile[1109:322396] cell.height-525.000000-

 

 

 

 

在有了estimatedHeight时,在iOS8下,delegate的调用顺序则又有所改变:

 

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPathNS_AVAILABLE_IOS(7_0);

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath;

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

 

 

 

==========自己在项目中的实现======

 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

 

    LYNormalLineThreeSelectCell *cell=[tableViewdequeueReusableCellWithIdentifier:identifierthree];//前三直选

 

  self.maxH=  [cellsetCell];//返回cell的高度,在cell中计算cell的实际高度,一定要强制layoutIfNeed(强制布局)后再返回。一定要在cell返回之前返回cell的高度

    NSLog(@"cell");

    return cell;

 

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    NSLog(@"cell的高度");

   

    NSLog(@"cell.height-%f-",self.maxH);

    returnself.maxH;//在cellforRow中返回的cell高度

 

}

 

 

==========实现预估高度

 

 

 

 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    

    CustomTableViewCell *cell = (CustomTableViewCell *)[self getCellFromIndexPath:indexPath];

    

    CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];

    

    return size.height +1;

    

}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{

    returnUITableViewAutomaticDimension;

}

 

 

systemLayoutSizeFittingSize,这个方法会根据autolayout计算出实际的高度,所以在设置约束的时候,一定要保证约束正确。

=====================

iOS 6之前预先在modal中计算cell的高度;

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context

 

========================

     cell.selectionStyle=UITableViewCellSelectionStyleNone;

        //自己定义cell选中的颜色

//        UIView *v=[[UIView alloc]init];

//        v.backgroundColor=[UIColor brownColor];

//        cell.selectedBackgroundView=v;

 

=================

// 确保cell的布局约束被设置好了,因为它可能刚刚才被创建好。    // 使用下面两行代码,前提是假设你已经在cell的updateConstraints方法中设置好了约束:    [cell setNeedsUpdateConstraints];    [cell updateConstraintsIfNeeded];    // 如果你使用的是多行的UILabel,不要忘了,preferredMaxLayoutWidth需要设置正确。    // 如果你没有在cell的-[layoutSubviews]方法中设置,就在这里设置。    // 例如:    // cell.multiLineLabel.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds);
 
 
// 触发cell的布局过程,会基于布局约束计算所有视图的frame。  // (注意,你必须要在cell的-[layoutSubviews]方法中给多行的UILabel设置好preferredMaxLayoutWidth值;  // 或者在下面2行代码前手动设置!)  [cell setNeedsLayout];  [cell layoutIfNeeded];

***************cell上图文混排实例--------动态计算cell高度========

#import 
@interface LYBInfoview : UIView@end
#import "LYBInfoview.h"#import "LYBInfotextAndImageCell.h"@interface LYBInfoview()
@property(nonatomic,strong)UITableView *tab;@property(nonatomic,strong)NSArray *infoArr;@property(nonatomic,assign)CGFloat cellHeight;//计算后返回的cell高度@endstatic  NSString  *const identi=@"infotextAndImagcell";@implementation LYBInfoview-(NSArray *)infoArr{    if(nil==_infoArr){        _infoArr=@[@{@"content":@"",                       @"imgcontent":@[@"eightewm",@"eightewm",@"eightewm",@"eightewm",@"fourewm",@"fourewm",@"fourewm"],                       @"nickname":@"我要发大财7",                       @"img":@"wodecai"                     },@{                       @"content":@"第二个哥哥恶搞额哥哥恶搞 恶搞恶搞恶搞恶搞 ",                       @"imgcontent":@[@"firstewm",@"firstewm",@"firstewm",@"firstewm",@"fourewm",@"fourewm"],                       @"nickname":@"我要发大财6",                       @"img":@"wodecai"                       },@{                       @"content":@"第说你是哪是哪是哪是哪是oiooijoidioaofdoi ",                       @"imgcontent":@[@"fiveewm",@"fiveewm",@"fiveewm",@"fiveewm",@"fourewm"],                       @"nickname":@"我要发大财5",                       @"img":@"wodecai"                       },@{                       @"content":@"第在 v 反倒是 v 反倒是 v 的方式 v 的方式 v 的方式 vfdoi ",                       @"imgcontent":@[@"fourewm",@"fourewm",@"fourewm",@"fourewm"],                       @"nickname":@"我要发大财4",                       @"img":@"wodecai"                       },@{                       @"content":@"第在 v 反倒是 v 反倒是 v 的方式 v 的方式 v 的方式 vfdoi ",                       @"imgcontent":@[],                       @"nickname":@"我要发大财0",                       @"img":@"wodecai"                       }];    }    return _infoArr;}-(instancetype)initWithFrame:(CGRect)frame{    if(self==[super initWithFrame:frame]){        [self initTabWith:frame];    }    return self;}-(void)initTabWith:(CGRect)frame{    UITableView *tab=[[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];    tab.delegate=self;    tab.dataSource=self;    self.tab=tab;    tab.estimatedRowHeight=44;    tab.rowHeight=UITableViewAutomaticDimension;    [self addSubview:tab];    [tab registerClass:[LYBInfotextAndImageCell class] forCellReuseIdentifier:identi];}-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{    return 1;}-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{        return self.infoArr.count;}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    LYBInfotextAndImageCell *cell=[tableView dequeueReusableCellWithIdentifier:identi];    if(self.infoArr.count>0){    NSDictionary *dict=self.infoArr[indexPath.row];  self.cellHeight =  [cell setcellWithDict:dict];    }    return cell;}-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{        return self.cellHeight;}@end
#import 
@interface LYBInfotextAndImageCell : UITableViewCell-(CGFloat)setcellWithDict:(NSDictionary *)dict;@property(nonatomic,assign)CGFloat texth;//文字的高度@end
#import "LYBInfotextAndImageCell.h"#import "Header.h"@interface LYBInfotextAndImageCell()@property(nonatomic,strong)UIImageView *imagV;//头像@property(nonatomic,strong)UIButton *nickBtn;//昵称@property(nonatomic,strong)UILabel *contetnlbl;//文字内容@property(nonatomic,strong)UIView *imgContentView;//放图片的view@property(nonatomic,strong)UIView *bottomView;//转发、点赞、评论@end@implementation LYBInfotextAndImageCell- (void)awakeFromNib {    [super awakeFromNib];}-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{    if(self==[super initWithStyle:style reuseIdentifier:reuseIdentifier]){        [self initCell];    }    return self;}-(void)initCell{    UIView *cellHeadview=[[UIView alloc]initWithFrame:CGRectMake(0, 10,WIDTH,100)];    UIImageView *imageV=[[UIImageView alloc]initWithFrame:CGRectMake(20, 0, 60, 60)];    self.imagV=imageV;    [cellHeadview addSubview:imageV];    UIButton *nickBtn=[UIButton wh_buttonWithTitle:@"我要发大财,今天买大乐透" backColor:nil backImageName:nil titleColor:[UIColor orangeColor] fontSize:14 frame:CGRectMake(80, 0, WIDTH/2, 30) cornerRadius:0];    nickBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;    self.nickBtn=nickBtn;    [cellHeadview addSubview:nickBtn];    [self addSubview:cellHeadview];       //显示文字内容的区域    UILabel *contetnlbl=[[UILabel alloc]initWithFrame:CGRectMake(20,90, WIDTH-40,10)];    contetnlbl.text=@"我要发大财";    contetnlbl.font=[UIFont systemFontOfSize:15];    contetnlbl.numberOfLines=0;    self.contetnlbl=contetnlbl;    [self addSubview:contetnlbl];        //存放图片的view    UIView *imgContentView=[[UIView alloc]initWithFrame:CGRectMake(20, 160, WIDTH-40, 10)];    self.imgContentView=imgContentView;//    imgContentView.backgroundColor=[UIColor redColor];    [self addSubview:imgContentView];    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];    [self.imgContentView addGestureRecognizer:tap];        //转发、评论、点赞    UIView  *bottomview=[[UIView alloc]initWithFrame:CGRectMake(0, 170, WIDTH-40, 50)];    self.bottomView=bottomview;    UIButton *shareBtn=[UIButton wh_buttonWithTitle:@"转发" backColor:[UIColor whiteColor] backImageName:@"" titleColor:[UIColor blackColor] fontSize:12 frame:CGRectMake(0, 0, WIDTH/3, 50) cornerRadius:0];    [shareBtn addTarget:self action:@selector(shareBtnclick:) forControlEvents:UIControlEventTouchUpInside];    [bottomview addSubview:shareBtn];    UIButton *commentBtn=[UIButton wh_buttonWithTitle:@"评论" backColor:[UIColor whiteColor] backImageName:@"" titleColor:[UIColor blackColor] fontSize:12 frame:CGRectMake(WIDTH/3, 0, WIDTH/3, 50) cornerRadius:0];    [commentBtn addTarget:self action:@selector(comment:) forControlEvents:UIControlEventTouchUpInside];    [bottomview addSubview:commentBtn];    UIButton *dianzanBtn=[UIButton wh_buttonWithTitle:@"点赞" backColor:[UIColor whiteColor] backImageName:@"" titleColor:[UIColor blackColor] fontSize:12 frame:CGRectMake(WIDTH*2/3, 0, WIDTH/3, 50) cornerRadius:0];     [dianzanBtn addTarget:self action:@selector(dianzan:) forControlEvents:UIControlEventTouchUpInside];    [bottomview addSubview:dianzanBtn];    [self addSubview:bottomview];}//手势-(void)tap:(UITapGestureRecognizer *)tap{      NSLog(@"tap");}//转发-(void)shareBtnclick:(UIButton *)btn{    btn.enabled=NO;    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{        btn.enabled=YES;    });    }//评论-(void)comment:(UIButton *)btn{    btn.enabled=NO;    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{        btn.enabled=YES;    });    }//点赞-(void)dianzan:(UIButton *)btn{    btn.enabled=NO;    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{        btn.enabled=YES;    });    }//设置cell上的内容哦-(CGFloat)setcellWithDict:(NSDictionary *)dict{    NSString *nickname=dict[@"nickname"];//昵称    [self.nickBtn setTitle:nickname forState:UIControlStateNormal];    self.imagV.image=[UIImage imageNamed:dict[@"img"]];//头像    self.contetnlbl.text=dict[@"content"];//文本内容    NSArray *imgArr=dict[@"imgcontent"];//图片名数组            //*****计算文本的高度 *******给显示的文本一个区域*****        CGSize contentMaxSizes = CGSizeMake(WIDTH-40, MAXFLOAT);        // NSFontAttributeName 字体的大小        NSDictionary *attributesDicts = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};    //计算文本实际宽高的时候, 计算的字体大小要和label中设置的字体大小保持一致        // 根据限定的条件, 来计算text 真实的宽高        CGSize contentRealSizes =  [self.contetnlbl.text boundingRectWithSize:contentMaxSizes options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDicts context:nil].size;        self.contetnlbl.height=contentRealSizes.height;// 重新设置frame        /*          单图会按照图片等比例显示          多图的图片大小固定          多图如果是4张,会按照 2 * 2 显示          多图其他数量,按照 3 * 3 九宫格显示          */    CGFloat imgcontentviewheight=0;    NSInteger w=(WIDTH-40)/3;    NSInteger count=imgArr.count;    NSInteger row=(count-1)/3+1;//确定行数    CGFloat h=0;//cell 的高度     self.imgContentView.y=CGRectGetMaxY(self.contetnlbl.frame);    if(imgArr.count==0){        self.imgContentView.height=imgcontentviewheight;    }else {        self.imgContentView.height=row*w;    }    //******清空imgContentView上的内容*******    if(self.imgContentView){        for (UIView *v in self.imgContentView.subviews) {            [v removeFromSuperview];        }    }    //***********创建图片    for(int i=0;i

==================动态计算cell2================

 

 

 

/** 动态计算ccell的高度 */#import 
NS_ASSUME_NONNULL_BEGIN@interface LYBAutoCaculateHeightTableview : UIView@property(nonatomic,strong)UITableView *tab;@property(nonatomic,strong)NSArray *dataArr;@endNS_ASSUME_NONNULL_END*********/** 动态计算ccell的高度 */#import "LYBAutoCaculateHeightTableview.h"#import "LYBAutoCaculateHeightCell.h"@interface LYBAutoCaculateHeightTableview()
@property(nonatomic,assign)CGFloat realHeight;//返回的动态计算的高度@end@implementation LYBAutoCaculateHeightTableview-(instancetype)initWithFrame:(CGRect)frame{ if(self=[super initWithFrame:frame]){ [self setTableviewWithFrame:(CGRect)frame]; } return self;}-(void)setTableviewWithFrame:(CGRect)frame{ self.dataArr=@[@"",@"",@"",@"",@"",@"",@"",@"",@"",@"",@""]; UITableView *tab=[[UITableView alloc]initWithFrame:CGRectMake(0, 0,frame.size.width , frame.size.height) style:UITableViewStylePlain]; self.tab=tab; tab.delegate=self; tab.dataSource=self; [self addSubview:tab]; [tab registerClass:[LYBAutoCaculateHeightCell class] forCellReuseIdentifier:@"autocaculateHeightcell"]; tab.tableFooterView=[[UIView alloc]init]; tab.estimatedRowHeight=100;// tab.rowHeight=UITableViewAutomaticDimension;}-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1;}-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return self.dataArr.count;}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ LYBAutoCaculateHeightCell *cell=[tableView dequeueReusableCellWithIdentifier:@"autocaculateHeightcell"]; NSDictionary *dict=@{@"content":@"dsafdsafdsafsafsfdsafdsafdsawon我问佛爱妃三大粉丝胡覅萨芬上的话法司法is还符号一摔赴死阿富汗一海商法ISAihihisfidsfiisdsafdsafdsafdsafdsaf",@"font":@"15"}; self.realHeight=[cell setDict:dict]; return cell; }- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ NSLog(@"--%f",self.realHeight); return self.realHeight;}-(NSArray *)dataArr{ if(nil==_dataArr){ _dataArr=[[NSArray alloc]init]; } return _dataArr;}@end*******/** 自动计算高度的cell */#import
NS_ASSUME_NONNULL_BEGIN@interface LYBAutoCaculateHeightCell : UITableViewCell-(CGFloat)setDict:(NSDictionary *)dict;//计算cell的高度@endNS_ASSUME_NONNULL_END*********#import "LYBAutoCaculateHeightCell.h"@interface LYBAutoCaculateHeightCell()@property(nonatomic,strong)UILabel *lbl;@end@implementation LYBAutoCaculateHeightCell- (void)awakeFromNib { [super awakeFromNib];}-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{ if(self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]){ [self createViews]; } return self;}-(void)createViews{ UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, [UIScreen mainScreen].bounds.size.width-20, self.frame.size.height)]; lbl.numberOfLines = 0;//表示label可以多行显示 self.lbl=lbl; [self addSubview:lbl];}//在这里面计算找各种view的大小,然后把高度返回去,这里只写了一个label举例说明-(CGFloat)setDict:(NSDictionary *)dict{ NSString *content=@""; if([[dict allKeys]containsObject:@"content"]){ content=dict[@"content"]; self.lbl.text=content; } CGFloat fontSize=15.f; if([[dict allKeys]containsObject:@"font"]){ fontSize=[dict[@"font"] floatValue]; self.lbl.font=[UIFont systemFontOfSize:fontSize]; } // 给 显示的文本一个区域CGSize contentMaxSizes = CGSizeMake([UIScreen mainScreen].bounds.size.width, MAXFLOAT);// NSFontAttributeName 字体的大小NSDictionary *attributesDicts = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};// 计算文本实际宽高的时候, 计算的字体大小要和label中设置的字体大小保持一致// 根据限定的条件, 来计算text 真实的宽高CGSize contentRealSizes =[self.lbl.text boundingRectWithSize:contentMaxSizes options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDicts context:nil].size;return contentRealSizes.height; // 方法二:用这个方法的时候,获取cell不能用[tableView CellforrowAtIndepath:indexPath]方法// [self layoutIfNeeded];// CGSize fittingSize = UILayoutFittingCompressedSize;// fittingSize.width = [UIScreen mainScreen].bounds.size.width;// CGFloat height = [self systemLayoutSizeFittingSize:fittingSize].height ;//// return height;}//这一步必须要,因为设置的labelg高度和cell一样,所以cell高度变了,要在这里重新布局label的高度-(void)layoutSubviews{ CGRect frame=self.lbl.frame; frame.size.height=self.frame.size.height; self.lbl.frame=frame;}@end

 

转载地址:http://lqlgi.baihongyu.com/

你可能感兴趣的文章
安装完 MySQL 后必须调整的 10 项配置
查看>>
开发者必备的 12 个 JavaScript 库
查看>>
http错误码
查看>>
python 多线程
查看>>
sipp命令 各参数含义
查看>>
搜集的动植物分类、检索网站
查看>>
ffmpeg源码分析之媒体打开过程
查看>>
Ubuntu/centos/redhat/SUSE sipp安装(带rtp支持,3.5.1版本)
查看>>
周鸿祎:很多程序员聪明,但我一看就知道他不会成功
查看>>
编译程序遇到问题 relocation R_X86_64_32 against `.rodata' can not be used when making a shared object;
查看>>
Const指针 、 指向const的指针 、引用、指针
查看>>
GDB调试命令
查看>>
常见数据类型的字节数
查看>>
gcc/g++ 编译常见问题
查看>>
【设计模式】 工厂模式实例 C++ , 利用工厂模式写一个计算器
查看>>
opencv
查看>>
【图像处理】 一、OSTU分割
查看>>
Android常用的框架有哪些
查看>>
SSL 证书创建与部署
查看>>
学习搭建人工智能环境遇到的问题
查看>>