1.第一步操作:
注意,下面的宽度的指定,使用约束左边右边或者直接约束宽度都可以。
2.代码如下:
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (nonatomic, copy) NSString *str;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self initData];
[self initUI];
}
#pragma mark - init
- (void)initData {
_str = @"asdhasiodhas dhasiudasidhasbkdj ahsdjkahsdjkasdh ajksdhas jkdahskjdhnasjk adhs ";
}
- (void)initUI {
//CGSize titleSize = [_str sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(320, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:20]};
// 动态获取label的size // 100限宽
CGSize titleSize = [_str boundingRectWithSize:CGSizeMake(100, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
_label.text = _str;
NSLog(@"%@", NSStringFromCGSize(titleSize));
_label.frame = CGRectMake(_label.frame.origin.x, _label.frame.origin.y, 100, titleSize.height);
}
@end