【问题标题】:Why does my UILabel frame code work in iOS 6 but not in iOS 7?为什么我的 UILabel 框架代码在 iOS 6 中有效,而在 iOS 7 中无效?
【发布时间】:2014-03-09 15:40:14
【问题描述】:

我在 iOS 5/6 应用程序中使用此代码已有很长时间了。它在viewWillAppear: 之下并操纵UILabel 高度,它可以根据需要容纳更多文本(并将其下方的其他标签向下推)。问题是,对于 iOS 7,它似乎不再工作了。文本根本不会换行到第二行。代码如下:

self.titleLabel.text = titleString;
self.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.titleLabel.numberOfLines = 0;

// Determine what the size of the title label should be
CGSize maximumLabelSize = CGSizeMake(163,66);
CGSize expectedLabelSize = [titleString sizeWithFont:self.titleLabel.font
                                           constrainedToSize:maximumLabelSize
                                            lineBreakMode:self.titleLabel.lineBreakMode];

// Adjust the the new height of the title label.
CGRect newFrame = self.titleLabel.frame;
newFrame.size.height = expectedLabelSize.height;
self.titleLabel.frame = newFrame;

NSLog(@"Title Height: %f", self.titleLabel.frame.size.height);

这里有更多信息。此UILabel 位于UITableView 的标题视图中。它是使用 Interface Builder 设计的,标签上带有 IBOutletUILabel 的属性在 iOS 6 和 iOS 7 项目中是相同的。

这是 Xcode 4 在 iOS 6 上运行时的样子:

这是带有 iOS 7 的 Xcode 5(如您所见,文本没有换行):

有人有什么想法吗?

【问题讨论】:

  • 你是否将UILabel上的行数设置为足够高的值?
  • iOS 7 中的文本渲染有人们注意到的怪癖,尝试给标签增加几个像素的高度(可能+5),看看它是否正确换行
  • 即使在高度上加上 + 10,仍然一无所获。就像标签变大了,但文本没有换行或出现在该区域中。

标签: ios objective-c xcode cocoa-touch uitableview


【解决方案1】:

就像@Jack Wu 说的,试着给标签增加几个像素。同样是iOS 7 sizeWithFont 已被boundingRectWithSize 取代:

GSize maximumLabelSize = CGSizeMake(163,66);
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:titleString attributes:@{NSFontAttributeName: self.titleLabel.font}];
CGRect rect = [attributedText boundingRectWithSize:maximumLabelSize
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                           context:nil];
CGSize expectedLabelSize = rect.size;

【讨论】:

    【解决方案2】:

    确保您的 UILabel 是显示文本所需的正确高度。

    然后确保您没有更改 UILabel 上的 numberOfLines。

    如果您希望 UILabel 使用尽可能多的行数,请将行数设置为 0

    myLabel.numberOfLines = 0;
    

    【讨论】:

    • 你在使用自动布局吗?
    • 不,不在该地区。
    • 您可能需要调整标题视图的高度,在添加之前检查您是否设置了它
    【解决方案3】:

    虽然您打印的是尺寸,但我想如果它不同,您会这么说。由于某些约束或调整大小选项,可能发生的情况是在显示时更改大小。您可以做的一件事来测试这是否是问题所在,即在标签上设置背景颜色,以查看它在垂直方向上的大小是否正确。还为标题视图设置背景颜色。我通常会这样做以确保物品的尺寸正确。

    另外,iOS7 不推荐使用 sizeWithFont: 方法。

    您可以使用我在这里得到的这个答案:

    UITableViewCell with UITextView height in iOS 7?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 2014-11-28
      • 2011-09-09
      • 2015-01-28
      • 2020-08-09
      • 2011-11-02
      • 1970-01-01
      相关资源
      最近更新 更多