iOS-个人整理19 - UITableViewCell自定义,cell高度的自适应

一、UITableViewCell的自定义

UITableVie中系统的Cell共提供了四种默认样式,
分别是:UITableVieCellStyleDefault //只有一个label
UITableVieCellStyleValue1 //两个label
UITableVieCellStyleValue2 //两个label,布局不同于上面的
UITableVieCellStyleSubtitle //带副标题但是在实际使⽤用过程中,Cell样式的布局上千差万别,

比如:

没错,聊天界面也是TableViewCell。
为了满足各种奇葩的需求和精美的设计,需要我们自定义cell
我们也就可以在一个tableView里放各种不同的Cell

方法也不复杂
首先创建一个继承于UITableViewCell的类CustomCell
在CustomCell.h中声明属性,这些属性就是要添加到自定义cell上的Label,ImageView等等

#import <UIKit/UIKit.h>  
@interface CustomCell : UITableViewCell   
@property (nonatomic,retain)UILabel* nameLabel;//显示名字  
@end  

然后在CustomCell.m中对声明对属性写好懒加载

#import "CustomCell.h"  
  
@implementation CustomCell  
  
//姓名标签的初始化  
-(UILabel *)nameLabel  
{  
    if (!_nameLabel) {  
        _nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(80, 10, 120, 30)];  
        [self.contentView addSubview:_nameLabel];  
    }  
    return _nameLabel;  
}  
@end  

最后在UITableView的注册单元格和填充单元格的代码中替换系统的UITableViewCell

 //注册单元格,在ViewDidLoad方法中  
  
    [self.tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"CELL"];    
    
//重用队列,这在单元格填充的方法内  
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  
  
   //这里用CustomCell替换原来的UITableViewCell  
   CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];  

}

总体思路就是这样,主要不同是这个cell怎么自定义,里面加多少label,imageView,怎么布局,就是个人的事了。

二、cell高度的自适应

有时候要根据内容调整cell的高度,要用到cell返回高度的代理方法

//返回高度的代理方法  
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  

还需要对内容的高度进行一定的计算,这里先提供一种计算文本宽高的方法
这是一个自写函数,核心是使用了系统的boundingRectWithSize:CGSizeMake(width,height) optins:() attributes:()context:方法
这个方法需要我们提供一个宽度一个高度,如果宽度设置为MaxFloat,高度给定,则最后计算出一个CGRect会根据内容content计算出相应的宽度。
同样,如果高度设置为MaxFloat,最后会计算出一个CGRect,其高度是根据content计算出的

options:这个参数比较重要

1.NSStringDrawingUsesLineFragmentOrigin:
绘制文本时使用 line fragement origin 而不是 baseline origin。
2.NSStringDrawingUsesFontLeading:
计算行高时使用行距。(字体大小+行间距=行距)
3.NSStringDrawingTruncatesLastVisibleLine:
如果文本内容超出指定的矩形限制,文本将被截去并在最后一个字符后加上省略号。如果没有指定NSStringDrawingUsesLineFragmentOrigin选项,则该选项被忽略。
4.计算布局时使用图元字形(而不是印刷字体)。
Use the image glyph bounds (instead of the typographic bounds) when computing layout.
attributes:文本属性,一个字典,里面包含了文字的各种属性,这里没细看,仅供参考
(1)NSKernAttributeName: @10 调整字句 kerning 字句调整
(2)NSFontAttributeName : [UIFont systemFontOfSize:_fontSize] 设置字体
(3)NSForegroundColorAttributeName :[UIColor redColor] 设置文字颜色
(4)NSParagraphStyleAttributeName : paragraph 设置段落样式
(5)NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.alignment = NSTextAlignmentCenter;
(6)NSBackgroundColorAttributeName: [UIColor blackColor] 设置背景颜色
(7)NSStrokeColorAttributeName设置文字描边颜色,需要和NSStrokeWidthAttributeName设置描边宽度,这样就能使文字空心.
context:上下文。包括一些信息,例如如何调整字间距以及缩放。最终,该对象包含的信息将用于文本绘制。但是没用过,还不懂,该参数可为 nil 。

#pragma mark -- 计算宽窄的函数  
-(float)autoCalculateWidthOrHeight:(float)height  
                             width:(float)width  
                          fontsize:(float)fontsize  
                           content:(NSString*)content  
{  
    //计算出rect  
    CGRect rect = [content boundingRectWithSize:CGSizeMake(width, height)   
                                        options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading   
                                     attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontsize]} context:nil];  
      
    //判断计算的是宽还是高  
    if (height == MAXFLOAT) {  
        return rect.size.height;  
    }  
    else  
        return rect.size.width;  
}  

有了上面这个看起来有点复杂的方法,我们就可以调用它计算出应有的宽或者高了


//计算出nameLabel的宽度,高度为20,字体大小为17  
  _nameWidth = [self autoCalculateWidthOrHeight:20 width:MAXFLOAT fontsize:17 content:name];  
//  RootTableViewController.m  
  
#import "RootTableViewController.h"  
#import "CustomTableViewCell.h"  
  
@interface RootTableViewController ()  
  
@property (nonatomic,retain)NSArray *contentArray;  
  
@end  
  
@implementation RootTableViewController  
  
- (void)viewDidLoad {  
    [super viewDidLoad];  
      
    self.navigationItem.title = @"自定义cell";        
    //注册cell  
    [self.tableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CELL"];  
           
}  
    
#pragma mark - Table view data source  
  
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {  
#warning Incomplete implementation, return the number of sections  
    return 1;  
}  
  
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {  
#warning Incomplete implementation, return the number of rows  
    return 3;  
}  
  
#pragma mark -- 单元格填充  
  
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];  
    cell.tag =1000;  
    //对cell填写内容  
    cell.newsImageView.image = [UIImage imageNamed:@"placeholder.jpg"];  
    cell.titleLabel.text = [NSString stringWithFormat:@"第%ld条",indexPath.row];  
    cell.abstractLabel.text = _contentArray[indexPath.row];  
    cell.commentNumLavel.text = @"1.6万跟帖";  
  
    return cell;  
}  
  
//返回单元格的高度  
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  
{  
    //数据数组  
    _contentArray = [[NSArray alloc]initWithObjects:@"不信这都不过。我是高二的文科生,政治学得不怎么样, 
老爸就叫我抄了老师的号码说是跟老师探讨怎么督促我学习什么的…。结果两个月后,政治老师被我爸拿下了………。- -!我现在更不知道政治该怎么办……。 ",  
@"听我们这的一位老师傅讲的。。。前面一辆宝马,开车的是个妹子,后面跟着一个皮卡,块红绿灯了,到路口,刚好黄灯,那妹子直接刹车,当然了,你们懂的, 
皮卡没反应过来,再加上刹车不如人宝马快,果断撞上了,其实要是个爷们开那宝马,黄灯也就闯过去了,那皮卡就这么想的。然后那妹子走下车来,看车撞了, 
蹲地上就哭。那皮卡里的少年出来愣了,扶着那妹子说,妹妹你别哭了,该哭的是我。。。 ",@"刚刚从台湾旅游回来,体会到了传说中的民风淳朴。。。。。 
默默地分割。。。。。。话说住在嘉义那天去夜市,找了一家店吃宵夜,点了一个特色的火鸡饭和卤肉饭,小碗那种,总共才40台币,十块rmb都不到, 
中途我出去买盐酥鸡,我朋友出去买饮料,吃完我们就抹抹嘴巴走了(我们都以为对方付过钱了)走到半路想起来落了围巾,回去拿,我跟店员打了招呼, 
拿好围巾出店门,想想不对,问朋友付钱没?她也摇头,于是回到店里问那个腼腆的小伙子,怎么不问我们收钱,他说:看你们刚刚走得急。。。", nil nil];  
      
    //根据内容计算高度  
    CGRect rect = [_contentArray[indexPath.row] boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.view.frame)-120, MAXFLOAT)   
            options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading   
            attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];  
    //再加上其他控件的高度得到cell的高度  
      
    return rect.size.height + 20 + 20;  
}      
@end  

自定义的cell

//  CustomTableViewCell.h  
  
#import <UIKit/UIKit.h>  
  
@interface CustomTableViewCell : UITableViewCell  
  
//创建三个label,一个imageView  
@property (nonatomic,retain)UILabel* titleLabel;//标题  
@property (nonatomic,retain)UILabel* abstractLabel;//摘要  
@property (nonatomic,retain)UILabel* commentNumLavel;//跟帖数量  
@property (nonatomic,retain)UIImageView* newsImageView;//新闻图片  
  
@end  
//  CustomTableViewCell.m  
  
#import "CustomTableViewCell.h"  
  
@implementation CustomTableViewCell  
  
#pragma mark -- 懒加载  
  
//左侧图片  
-(UIImageView *)newsImageView  
{  
    if (!_newsImageView) {  
        _newsImageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 10, 80, 80)];  
        [self.contentView addSubview:_newsImageView];  
        _newsImageView.image = [UIImage imageNamed:@"placeholder.jpg"];  
        //设置圆角  
        _newsImageView.layer.cornerRadius = 5;  
        _newsImageView.layer.masksToBounds = YES;  
    }  
    return _newsImageView;  
}  
  
//标题  
-(UILabel *)titleLabel  
{  
    if (!_titleLabel) {  
        _titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 5, CGRectGetWidth(self.frame)-120, 20)];  
        [self.contentView addSubview:_titleLabel];  
        _titleLabel.backgroundColor = [UIColor colorWithRed:247/255.0 green:162/255.0 blue:120/255.0 alpha:1];  
    }  
    return _titleLabel;  
}  
  
//摘要  
-(UILabel *)abstractLabel  
{  
    if (!_abstractLabel) {  
        _abstractLabel = [[UILabel alloc]initWithFrame:CGRectMake(100, 25, CGRectGetWidth(self.frame)-120, 70)];  
        [self.contentView addSubview:_abstractLabel];  
        _abstractLabel.backgroundColor =  [UIColor colorWithRed:200/255.0 green:233/255.0 blue:160/255.0 alpha:1];  
          
        //设置行数,这里很重要,0意味着行数自适应  
        _abstractLabel.numberOfLines = 0;  
          
        //设置字体  
        _abstractLabel.font = [UIFont fontWithName:@"28=蒙纳幼雅丽" size:15];  
    }  
      
    //根据cell重新调整label的高度  
    CGRect labelRect = _abstractLabel.frame;  
    labelRect.size.height = CGRectGetHeight(self.frame)-20-20;  
    _abstractLabel.frame = labelRect;  
      
    return _abstractLabel;  
}  
//跟帖数  
-(UILabel *)commentNumLavel  
{  
    if (!_commentNumLavel) {  
        _commentNumLavel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetWidth(self.frame)-100,   
         CGRectGetHeight(self.frame)-20, 80, 15)];  
        [self.contentView addSubview:_commentNumLavel];  
        _commentNumLavel.backgroundColor = [UIColor colorWithRed:109/255.0 green:211/255.0 blue:206/255.0 alpha:1];  
          
        //设置字体  
        _commentNumLavel.font = [UIFont fontWithName:@"testfont" size:12];  
    }  
    return _commentNumLavel;  
}      
@end  

效果

三、在可视化下让cell自适应高度

在使用xib或者storyBoard时,同样可以在heightForCell的代理方法里调整cell的高度
但是cell上面的label要同时改变大小,就有所不同。
可以使用拉约束的方法,如图我这里是一个UITableViewCell的xib文件,给上面的contentLabel拉了四个约束,具体怎么拉看autolayout
分别规定了这个Label 到cell上边缘的距离,到cell下边缘的距离,到cell左边缘的距离,已经label的width给定值。
这样,cell的高度变化,label为随之变化

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

推荐阅读更多精彩内容