zoukankan      html  css  js  c++  java
  • cell自适应高度

    cell自适应高度

    方式一:在自定义cell的自适应高度

    1、在自定义cell的.h文件中声明两个类方法

    //求一段文本的显示高度

    + (CGFloat)heightForString:(NSString *)string;

    //求cell的高度

    + (CGFloat)cellHeightForStudent:(Student *)student;

    2、在自定义cell的.m文件中写方法的实现

    //求一段文本的显示高度

    + (CGFloat)heightForString:(NSString *)string {

        

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

        

        CGRect rect = [string boundingRectWithSize:CGSizeMake(3 *kImageWidth, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];

        return rect.size.height;

    }

    //返回cell的高度

    + (CGFloat)cellHeightForStudent:(Student *)student {

        CGFloat totalHeight = 65 + [GirlTableViewCell heightForString:student.introduce];

        return  totalHeight > 120 ? totalHeight : 120;

    }

    3、遵循协议- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath设定cell的高度

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

            return [MyTableViewCell cellHeightForStudent:student];

    }

    4、在自定义cell的LayoutSubViews方法中设定子视图的高度

    _introduceLabel.frame = CGRectMake(10, 65, 3 * imageWidth, [MyTableViewCell heightForString:self.student.introduce]);

    方式二:系统cell的自适应高度

    1、文本自适应高度,根据文本内容设定高度

    NSString *str = @“dibibfnbdfbiehiehiorjogjteobjoebmtlrmnklgrou9q7924529854038510280ifopkwolvbnnbeijoejorjgesgfndbkndfbivjfi” ; 

    // 获取字体样式属性

          NSDictionary *att = @{NSFontAttributeName:[UIFont

      systemFontOfSize:17.0]};

    // 根据字体样式属性获取高度

          CGRect rect = [str boundingRectWithSize:CGSizeMake(200, 10000) options:NSStringDrawingUsesLineFragmentOrigin  attributes:att context:nil];

          [self.showLabel setFrame:CGRectMake(0, 0, 200, rect.size.height)];

    2、图片自适应高度,根据图片宽度进行等比缩放

    UIImage *aImage = [UIImage imageNamed:@"1.png"]; 

    // 获取图片真实高度
    CGFloat height = aImage.size.height;
    CGFloat width = aImage.size.width; 

    // 缩放后宽度固定为150
    CGFloat scale = width / 150;
    CGFloat realHeight = height / scale;

     [self.myImageView setFrame:CGRectMake(0, 0, 200,realHeight)];

  • 相关阅读:
    洛谷P1170 兔八哥与猎人 欧拉函数的应用
    洛谷P1056 排座椅
    洛谷P1177 【模板】快速排序
    洛谷1059 明明的随机数
    洛谷P1372 又是毕业季I
    洛谷P1042 乒乓球
    洛谷P1086 花生采摘
    洛谷P1031 均分纸牌
    洛谷P1068 分数线划定
    洛谷P1781 宇宙总统
  • 原文地址:https://www.cnblogs.com/d-mm/p/5210181.html
Copyright © 2011-2022 走看看