iOS中对UITableView中的cell设置自动适应行高

该问题主要针对的是自定义tableView的cell时,在cell上添加一个UILabel用于显示内容时,由于内容的多少无法预知,所以我们要根据label上显示的文本的多少来设置cell的自动适应行高

1,首先 先创建自定义的cell(taleview根据自己的需求进行创建)

在.h中写属性和方法的声明

@interface CustomTableViewCell : UITableViewCell
@property (nonatomic, retain) UILabel *storyLabel;
//根据传入的文本计算cell的高度
 + (CGFloat)heightOfString:(NSString *)aString;
//根据传入的文本重新设置Label的frame
 - (void)resetLablFrame:(NSString *)aString;

在.m中

宏定义控件的基本属性

#import "CustomTableViewCell.h"
#define PLACE 10 //cell上控件之间以及和边界间的间距
#define HIGHT 120 //storyLabel的高度
@implementation CustomTableViewCell

创建一个label,添加到cell上

self.storyLabel = [[UILabel alloc] initWithFrame:CGRectMake( PLACE ,  PLACE , 300 , HIGHT)];
        _storyLabel.numberOfLines = 0;
        [self addSubview:_storyLabel];
        [_storyLabel release];

实现第一个方法

其中 CGSizeMake(300, 0)中的第一个参数是storyLabel的宽度 第二个参数0是高度,由于高度是未知的所以设置为0

+ (CGFloat)heightOfString:(NSString *)aString
{
    CGRect rect = [aString boundingRectWithSize:CGSizeMake(300, 0) options:NSStringDrawingUsesLineFragmentOrigin | 
       NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}  context:nil];
    return rect.size.height + 2 * PLACE ;
}
- (void)resetLablFrame:(NSString *)aString
{
    CGRect rect = [aString boundingRectWithSize:CGSizeMake(300, 0) options:NSStringDrawingUsesLineFragmentOrigin | 
NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]}  context:nil];
    
    CGRect frame = _storyLabel.frame;
   //重新设定storylabel的frame
 _storyLabel.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, rect.size.height);
}

完成上面的步骤,我们就做完了设置工作,那么只需要调用的时候传入参数就可以实现了 那么下面就将演示如何运用

在创建cell的时候,给方法进行赋值,这样就可以计算cell的高度

在代理方法中实现返回cell的行高











 
 
原文地址:https://www.cnblogs.com/nsjelly/p/4314255.html