4

我正在尝试调整 UILabel 的大小以适应 NSString 的范围,但我在 iOS 7.0.3 和 iOS 7.1.1 中看到了不同的结果。正如您在下面看到的,iOS 7.0.3 似乎无法正确绘制文本。

示例 1:文本被绘制到标签的底部,几乎在边界之外:

在此处输入图像描述

示例 2:文本绘制在 1 行(而不是 2 行)上,并且没有发生自动换行,只有尾部截断。

在此处输入图像描述

这是我用于上面列出的两个 iOS 版本的代码。

CGSize boundingSize = CGSizeMake(214, 9999);
CGRect boundingRect = CGRectZero;
[self.nameLabel setNumberOfLines:2];

// for iOS7
if([self.place.placeName respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]){
    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];

    boundingRect = [self.place.placeName boundingRectWithSize:boundingSize
                                                      options:NSStringDrawingUsesLineFragmentOrigin
                                                   attributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                               self.nameLabel.font, NSFontAttributeName,
                                                               paragraphStyle, NSParagraphStyleAttributeName, nil]
                                                      context:nil];

}else{
    // pre iOS7
    CGSize size = [self.place.placeName sizeWithFont:self.nameLabel.font constrainedToSize:boundingSize lineBreakMode:NSLineBreakByWordWrapping];
    boundingRect = CGRectMake(0, 0, size.width, size.height);
}

[self.nameLabel setFrame:CGRectMake(CGRectGetMaxX(self.photoImageView.frame)+15,
                                    CGRectGetMinY(self.photoImageView.frame),
                                    boundingRect.size.width, boundingRect.size.height)];

[self.nameLabel setText:[place placeName]];

有任何想法吗?提前致谢。

4

3 回答 3

3

我已就此问题联系 Apple,他们已确认这是 iOS 7.0.3 的错误,已在 iOS 7.1.1 中修复。

该问题的解决方法(我曾经使用过)是创建自己的 UILabel 子类,覆盖 - (void)drawTextInRect: 方法,并使用 NSString 的 - (void)drawInRect:withAttributes: 来呈现字符串。(苹果开发者)

于 2014-05-17T09:05:48.623 回答
0

只是猜测。从屏幕截图看起来,较短的标签是文字包装的,这表明宽度太短了。从一个 iOS 版本到另一个版本,调用的实现似乎以boundingRectWithSize某种微妙的方式发生了变化。它也可能与动态字体有关,谁知道呢。

以下是您应该尝试/检查的几件事:

  • 确保该numberOfLines属性设置为 0(或至少一个足够高的数字以允许换行,即不是1.
  • 给出boundingRect允许的最大宽度。
  • 检查自动布局约束是否在稍后阶段更改标签的框架
于 2014-05-09T09:12:19.813 回答
0

使用 numberOfLines 属性设置为至少足够高的数字以允许换行,即 labelheight/20(更改大小和测试)。

于 2014-05-17T09:15:37.983 回答