动态计算UILabel的尺寸

在无法确定一个UILabel对象中有多少文字的时候,是不能直接通过uiLabel.frame.size获取尺寸的,所以要通过如下方法:

#import "ViewController.h"

//先定义好字体大小的宏
#define TITLE_FONT [UIFont systemFontOfSize:20]
#define CONTENT_FONT [UIFont systemFontOfSize:14]

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UILabel *titleLabel;
@property (strong, nonatomic) IBOutlet UILabel *contentLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //计算单行文字,比如文章的标题
    NSString *titleStr = @"Title";
    NSDictionary *titleAtt = @{NSFontAttributeName:TITLE_FONT};
    CGSize titleSize = [titleStr sizeWithAttributes:titleAtt];
    CGFloat titleWidth = titleSize.width;
    CGFloat titleHeight = titleSize.height;
    self.titleLabel.text = titleStr;
    self.titleLabel.frame = CGRectMake((self.view.frame.size.width - titleWidth) * 0.5, 30, titleWidth, titleHeight);
    self.titleLabel.backgroundColor = [UIColor redColor];

    //计算多行文子,比如正文
    NSString *content = @"2016-10-27 23:57:38.710035 GetLabelSizeTest[5042:255006] subsystem: com.apple.UIKit, category: HIDEventFiltered, enable_level: 0, persist_level: 0, default_ttl: 0, info_ttl: 0, debug_ttl: 0, generate_symptoms: 0, enable_oversize: 1, privacy_setting: 2, enable_private_data: 0";
    CGFloat contentWidth = 300;
    NSDictionary *contentAtt = @{NSFontAttributeName:CONTENT_FONT};
    CGSize contentSize = CGSizeMake(contentWidth, MAXFLOAT);
    CGFloat contentHeight = [content boundingRectWithSize:contentSize options:NSStringDrawingUsesLineFragmentOrigin attributes:contentAtt context:nil].size.height;
    self.contentLabel.text = content;
    self.contentLabel.frame = CGRectMake((self.view.frame.size.width - contentWidth) * 0.5, self.titleLabel.frame.origin.y + self.titleLabel.frame.size.height + 30, contentWidth, contentHeight);
    self.contentLabel.backgroundColor = [UIColor redColor];
}
@end

results matching ""

    No results matching ""