·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> app软件开发 >> IOS开发 >> 在UILabel内计算内容的大小

在UILabel内计算内容的大小

作者:佚名      IOS开发编辑:admin      更新时间:2022-07-23

//  UILabel+LM.h

//
//  UILabel+LM.h
//  Test
//
//  Created by 李蒙 on 14-3-21.
//  Copyright (c) 2014年 datangcloud. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UILabel (LM)

- (CGSize)contentSize;

@end

 

//  UILabel+LM.m

//
//  UILabel+LM.m
//  Test
//
//  Created by 李蒙 on 14-3-21.
//  Copyright (c) 2014年 datangcloud. All rights reserved.
//

#import "UILabel+LM.h"

@implementation UILabel (LM)

- (CGSize)contentSize
{
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = self.lineBreakMode;
    paragraphStyle.alignment = self.textAlignment;
    
    NSDictionary * attributes = @{NSFontAttributeName : self.font,
                                  NSParagraphStyleAttributeName : paragraphStyle};
    
    CGSize contentSize = [self.text boundingRectWithSize:self.frame.size
                                                 options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                              attributes:attributes
                                                 context:nil].size;
    return contentSize;
}

@end