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:],
NSForegroundColorAttributeName:[UIColor redColor]
}; UILabel *titleLabel = [UILabel new];
titleLabel.text = @"德玛西亚万岁,断剑重铸之日,骑士归来之时,我们要以困难的方式搞定他。我本可以打的轻一点!";
titleLabel.numberOfLines = ;//多行显示,计算高度
titleLabel.textColor = [UIColor blackColor];
titleLabel.backgroundColor = [UIColor greenColor];
CGSize titleSize = [titleLabel.text boundingRectWithSize:CGSizeMake(, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes1 context:nil].size;
titleLabel.frame = CGRectMake(, , titleSize.width, titleSize.height); [self.view addSubview:titleLabel];
效果图如下: