UILabel 自适应宽高
Posted 甘林梦的开发之路
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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"
以上是关于UILabel 自适应宽高的主要内容,如果未能解决你的问题,请参考以下文章