·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> IOS-动态计算文本的宽度,来定义控件的frame大小。

IOS-动态计算文本的宽度,来定义控件的frame大小。

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

//根据传过来的文字内容,文字大小,和最大尺寸动态计算文字所占用的size

- (CGSize)labelAutoCalculateRectWith:(NSString*)text FontSize:(CGFloat)fontSize MaxSize:(CGSize)maxSize

{

    NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc]init];

   paragraphStyle.lineBreakMode=NSLineBreakByWordWrapping;

    NSDictionary* attributes =@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSParagraphStyleAttributeName:paragraphStyle.copy};

    //如果系统为iOS7.0;

    CGSize labelSize;

    if (![text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]){

        labelSize = [text sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:maxSize lineBreakMode:NSLineBreakByWordWrapping];

    }

//如果是IOS6.0

    else

  {

        labelSize = [text boundingRectWithSize: maxSize

                                       options: NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading|NSStringDrawingTruncatesLastVisibleLine

                                    attributes:attributes

                                       context:nil].size;

    }

    labelSize.height=ceil(labelSize.height);    

    labelSize.width=ceil(labelSize.width);

    return labelSize;

}

 

//调用的函数

   CGSize maxSize = CGSizeMake(MAXFLOAT, 40);

   CGSize titleSize = [self labelAutoCalculateRectWith:_publicDetail.name FontSize:15.0f MaxSize:maxSize];

 UILabel *label = [UILabel alloc]init];

 label.frame = CGRectMake(0 , 0, titleSize.width, titleSize.height);