Label自适应高度与自适应宽度
创建一个Category。
新建file->Objective—C File->下一步

File Type选择:Category
Class :UILabel
下一步。

在.h文件中添加两个方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font;
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont*)font;
|
.m文件中实现相应的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| + (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; }
|
使用方法:
这里结合的是自定义cell。
1 2 3
| cell.userName.text = _dataArray1[indexPath.row]; CGFloat width = [UILabel getWidthWithTitle:cell.userName.text font:cell.userName.font]; cell.userName.frame = CGRectMake(5, 5, width, 30);
|
实现的效果:
两个Label连在一起,前面的Label的宽度要根据内容自适应,最后实现了想要的效果。
