iOS开发: UITableViewCell的自适应高度

来源:互联网 发布:sunday算法 编辑:程序博客网 时间:2024/06/05 06:46


1、在cell.h文件下:定义一个Label,用来放cell的内容:

@property(nonatomic, retain)UILabel *countLabel;


2、在cell.m文件下:初始化label:

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{


    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

        [self createViews];

    }

    return self;

}

//为了封装,减少代码冗余,尽量调用自写方法

- (void)createViews{

    

    _countLabel = [[UILabel alloc]init];

    

    [self.contentView addSubview:_countLabel];

    

    [_countLabel release];

}


- (void)layoutSubviews{


    [super layoutSubviews];

    _countLabel.frame = CGRectMake(0, 0, 345, self.contentView.frame.size.height);

    _countLabel.font = [UIFont systemFontOfSize:15];

    _countLabel.numberOfLines = 0;


}

3、 在viewController.m文件中自定义cell的高度(两个协议方法自行实现):

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

 NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], NSFontAttributeName, nil];

//自适应cell的高度

(1)、需要一个size:(适度的width( <=375(iPhone6), 其实也无所谓了,最后要的是高度,可能对宽度的影响不会太大。), 尽可能高的height(最高的cgfloat_max))

(2)、option:有四种,一般选择第二个

NSStringDrawingTruncatesLastVisibleLine

   NSStringDrawingUsesLineFragmentOrigin 

   NSStringDrawingUsesFontLeading 

   NSStringDrawingUsesDeviceMetrics  

(3)、需要一个字典:初始化一个字典,可以添加修改字体大小、颜色什么的

        CGRect rect = [_activity.content boundingRectWithSize:CGSizeMake(375, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];

//重点:返回rect的高度,最重要的是要+1(系统自带bug), 不然会出现打印不全的情况(会出现......);如果说非不想+1,那就参考我上次写的,在定义一个string,把整个内容赋值给string,然后重写setter方法中实现上述cell自适应高度的过程。

        return  rect.size.height + 1;

    }







1 0
原创粉丝点击