ios - boundingRectWithSize :options:attributes:context: is not returning accurate expected UILabel size

标签 ios objective-c iphone width uilabel

我正在编写一个 iPhone 应用程序,我在其中创建一个在运行时具有动态内容的 UILabel。我无法控制 UILabel 的内容,因此我必须计算它的大小,以便稍后可以使用这些大小值来设置一些 UI 约束。

我正在使用以下代码创建 UILabel 并计算其预期大小:

UILabel *titleLabel = [[UILabel alloc] init];

titleLabel.font = [UIFont fontWithName:@"Arial-Bold" size:20];
titleLabel.numberOfLines = 0;
titleLabel.text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vulputate venenatis justo in ultrices. Pellentesque eu pharetra elit, id faucibus mi.";


//Calculate the expected lable size
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
CGFloat contentWidth = applicationFrame.size.width - 20; // 20 is 10+10, a margin of 10 from each side

CGSize maximumLabelSize = CGSizeMake(contentWidth, FLT_MAX); // FLT_MAX here simply means max possible height

CGRect expectedLabelSize = [titleLabel.text boundingRectWithSize:maximumLabelSize
                                                         options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                                      attributes:@{
                                                                   NSFontAttributeName:titleLabel.font
                                                                   }
                                                         context:nil];

当我运行上面的代码时,值 expectedLabelSize.size.width 有时比传递给 boundingRectWithSize:options:attributes 的原始 contentWidth 值大:上下文:。如何确保 contentWidth 是最大宽度?这很重要,因为我稍后会在某些约束中使用这些值,并且此最大宽度保持不变很重要。

谢谢。

最佳答案

Apple's reference ,有一个有趣的讨论:

This method returns the actual bounds of the glyphs in the string. Some of the glyphs (spaces, for example) are allowed to overlap the layout constraints specified by the size passed in, so in some cases the width value of the size component of the returned CGRect can exceed the width value of the size parameter.

这应该是您正在寻找的。结果宽度是否比您提供的“最大值”大很多?如果不是,我想讨论会回答你。

关于ios - boundingRectWithSize :options:attributes:context: is not returning accurate expected UILabel size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26596062/

相关文章:

iPhone 使用 NSURLConnection 发送 POST

iOS:将圆形切片动画化为更宽的切片

ios - iphone 应用程序图标 ios 7,8 (3x) for iphone 6

ios - 如何在 iOS(例如 iPhone)中保存 .plist 文件?

ios - 绕圈旋转

iphone - 使用 Core Data 时如何正确设置 NSPredicate 来实现一对多关系?

ios - 如何更改tableCell 的imageView 的frame?

ios - UITableViewCell 自定义(拉伸(stretch))背景使用 UIAppearance

objective-c - NSMutableArray addObject 不影响计数?

iphone - iPhone:应用程序新版本未出现在“AppStore更新”列表中!