UILabel 自适应宽高

#import <UIKit/UIKit.h>

@interface UILabel (UILabel_LabelHeighAndWidth)
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont*)font;

+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font;
@end
#import "UILabel+UILabel_LabelHeighAndWidth.h"

@implementation UILabel (UILabel_LabelHeighAndWidth)
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont *)font // 自适应高
{
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    label.text = title;
    label.font = font;
    label.numberOfLines = 0;
    [label sizeToFit];
    CGFloat height = label.frame.size.height;
    return height;
}

+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font {// 自适应宽
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 0)];
    label.text = title;
    label.font = font;
    [label sizeToFit];
    return label.frame.size.width;
}
@end

例如:CGFloat width1 = [UILabel getWidthWithTitle:strzhengcahngshu font:cell.zhengchangLabel.font];

        cell.zhengchangshuLabel.frame = CGRectMake(46, 60, width1, 15);

        cell.zhengchangshuLabel.text = strzhengcahngshu;

 说明:记得引入头文件

#import "UILabel+UILabel_LabelHeighAndWidth.h"

posted @ 2016-08-27 11:08  甘林梦  阅读(1069)  评论(0编辑  收藏  举报