Label的高度自适应和UItableViewCell的高度自适应

可以先写一个NSString 的拓展,计算nsstring的高度

@interface NSString (Ext)
- (CGSize)calculateSize:(CGSize)size font:(UIFont *)font;
@end


#import "NSString+Ext.h"

@implementation NSString (Ext)

- (CGSize)calculateSize:(CGSize)size font:(UIFont *)font {
    CGSize expectedLabelSize = CGSizeZero;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
        NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
        
        expectedLabelSize = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    }
    else {
        expectedLabelSize = [self sizeWithFont:font
                             constrainedToSize:size
                                 lineBreakMode:NSLineBreakByWordWrapping];
    }
    
    return CGSizeMake(ceil(expectedLabelSize.width), ceil(expectedLabelSize.height));
}


@end


在自定义一个cell

#import <UIKit/UIKit.h>

@interface Cell1 : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *titleLable;

@end

#import "Cell1.h"

@implementation Cell1

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib
{
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


最终是一个tableviewcell的自适应

#import <UIKit/UIKit.h>

@interface WhyViewController : UITableViewController

@property (nonatomic, strong) UITableViewCell *prototypeCell;

@end

#import "WhyViewController.h"
#import "Cell1.h"

#import "NSString+Ext.h"
@interface WhyViewController ()
{
    NSMutableArray *dataArray;
}
@end

@implementation WhyViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //xib需要注册单元格
//    UINib *cellNib = [UINib nibWithNibName:@"Cell1" bundle:nil];
//    [self.tableView registerNib:cellNib forCellReuseIdentifier:@"Cell1"];
    
    //获取一个单元格对象
    self.prototypeCell  = [self.tableView dequeueReusableCellWithIdentifier:@"Cell1"];
    
    //数据源
    dataArray = [NSMutableArray arrayWithObjects:@"手动方式【动态计算UITableViewCell高度】",@"UILabel的属性Lines这儿设为了0表示显示多行,将视图的AutoLayout去掉",@"本小段教程将介绍UILabel在Manual layout cell中计算高度, 原理是根据字体与字符串长度来计算长度与宽度。这儿用到了一个NSString的Cagetory方法",@"UITableView是一次性计算完所有Cell的高度,如果有1W个Cell,那么- (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath就会触发1W次,然后才显示内容。不过在iOS7以后,提供了一个新方法可以避免这1W次调用,它就是- (CGFloat)tableView:(UITableView )tableView estimatedHeightForRowAtIndexPath:(NSIndexPath )indexPath。要求返回一个Cell的估计值,实现了这个方法,那只有显示的Cell才会触发计算高度的protocol.", nil];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [dataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Cell1 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"Cell1"];
   
    NSString *content = [dataArray objectAtIndex:[indexPath row]];
   
    cell.titleLable.text = content;
    
    //动态调整Lable高度
    CGSize newSize = [content calculateSize:CGSizeMake(cell.titleLable.frame.size.width, FLT_MAX) font:cell.titleLable.font];
    CGRect rect = cell.titleLable.frame;
    rect.size = newSize;
    cell.titleLable.frame = rect;
    
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //获得一个单元格
    Cell1 *cell = (Cell1 *)self.prototypeCell;
    
    //当前字符串
    NSString *content = [dataArray objectAtIndex:indexPath.row];
    
    //获取lable动态高度
    CGSize newSize = [content calculateSize:CGSizeMake(cell.titleLable.frame.size.width, FLT_MAX) font:cell.titleLable.font];
    
    CGFloat defaultHeight = cell.contentView.frame.size.height;
    
    CGFloat height = newSize.height > defaultHeight ? newSize.height : defaultHeight;
    
    //返回cell的总高度
    return height + cell.titleLable.frame.origin.y;
}

//下面这个方法是为了提高程序性能,假如cell有N多行,- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath就会执行N次,而函数会给cell高度设置一个默认高度,当页面显示哪些cell时,才会调用- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath改变cell高度
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值