码迷,mamicode.com
首页 > 移动开发 > 详细

ios7之后 根据UILabel的文字计算frame的方法

时间:2015-10-22 14:18:05      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

ios7 新出来的根据label的文字和字体大小来确定label的宽高。

官方的方法是:

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(7_0);

其中NSStringDrawingOptions有四个枚举值:

typedef NS_OPTIONS(NSInteger, NSStringDrawingOptions) {

 // 如果文本内容超出指定的矩形限制,文本将被截去并在最后一个字符后加上省略号。如果没有指定NSStringDrawingUsesLineFragmentOrigin选项,则该选项被忽略

    NSStringDrawingTruncatesLastVisibleLine = 1 << 5, // Truncates and adds the ellipsis character to the last visible line if the text doesn‘t fit into the bounds specified. Ignored if NSStringDrawingUsesLineFragmentOrigin is not also set.

  // 绘制文本时使用 line fragement origin 而不是 baseline origin

    NSStringDrawingUsesLineFragmentOrigin = 1 << 0, // The specified origin is the line fragment origin, not the base line origin

  // 计算行高时使用行距。(译者注:字体大小+行间距=行距)

    NSStringDrawingUsesFontLeading = 1 << 1, // Uses the font leading for calculating line heights

  // 计算布局时使用图元字形(而不是印刷字体)。

    NSStringDrawingUsesDeviceMetrics = 1 << 3, // Uses image glyph bounds instead of typographic bounds

} NS_ENUM_AVAILABLE_IOS(6_0);

 

attributes是文本字体的属性:该参数要设置字体的大小。

context是上下文对象,用于包含信息:如何调整字间距以及缩放。最终,该对象包含的信息将用于文本绘制。该参数可为 nil。 

 

    NSDictionary *attributes1 = @{NSFontAttributeName:[UIFont systemFontOfSize:20],
                                  NSForegroundColorAttributeName:[UIColor redColor]
                                  };
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text =  @"德玛西亚万岁,断剑重铸之日,骑士归来之时,我们要以困难的方式搞定他。我本可以打的轻一点!";
    titleLabel.numberOfLines = 0;//多行显示,计算高度
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.backgroundColor = [UIColor greenColor];
    CGSize titleSize = [titleLabel.text boundingRectWithSize:CGSizeMake(300, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes1 context:nil].size;
    titleLabel.frame = CGRectMake(10, 64, titleSize.width, titleSize.height);
    
    [self.view addSubview:titleLabel];

 

效果图如下:

技术分享

 

ios7之后 根据UILabel的文字计算frame的方法

标签:

原文地址:http://www.cnblogs.com/Mr-Ygs/p/4900475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!