1. 需求:
根据字符串,字体,计算UILabel宽度
根据字符串,字体,宽度,计算UILabel高度
2. 解决:
新建一个分类Category,封装好相关计算方法
调用时,导入该分类,调用相关计算方法得出数值
3. 实现示例:
UILabel+Size分类,实现代码
UILabel+Size.h
//
// UILabel+Size.h
// xiaoanproduct
//
// Created by ChenMan on 2018/1/25.
// Copyright © 2018年. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UILabel (Size)
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont*)font;
+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font;
@end
UILabel+Size.m
//
// UILabel+Size.m
// xiaoanproduct
//
// Created by ChenMan on 2018/1/25.
// Copyright © 2018年. All rights reserved.
//
#import "UILabel+Size.h"
@implementation UILabel (Size)
+ (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
4. 调用示例:
场景:在一个UITableViewCell中,重写Cell的一个模型属性的setter方法,需要先对UILabel对象的text属性赋值后,再进行更新布局约束操作。代码如下:
CMTestTableViewCell.m
- (void)setCellMdl:(SupplementCellModel *)cellMdl{
if (cellMdl) {
_cellMdl = cellMdl;
self.titleLabel.text = cellMdl.titleStr;
self.contextTextField.placeholder = cellMdl.holderStr;
self.rightLbl.text = cellMdl.tailStr;
CGFloat width = [UILabel getWidthWithTitle:self.rightLbl.text font:self.rightLbl.font];
[self.rightLbl mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(width);
}];
self.kind = cellMdl.cellType;
}
}
作者:陈满iOS
链接:https://www.jianshu.com/p/c26c168efe45