【问题标题】:How do I properly use NSString sizeWithFont constratinedToSize with NIAttributedLabel如何正确使用 NSString sizeWithFont constratinedToSize 和 NIAttributedLabel
【发布时间】:2012-07-13 07:54:41
【问题描述】:

我已经浏览了关于 SO 上关于这种方法的每篇文章的感觉。 很多张贴者的答案只是将一个非常大的值作为高度约束。

但是,对我来说这不起作用。这是我的代码:

//Create the contentLabel Label
    CGSize size = [contentText sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] constrainedToSize:CGSizeMake(286, 9999) lineBreakMode:UILineBreakModeWordWrap];

    //Create the content label with its position 7 pixels below the title 
    contentLabel = [[NIAttributedLabel alloc] initWithFrame:
                   CGRectMake(7, titleContainerView.frame.origin.y + 7, 286, size.height)];

    //Set the provided text and the font
    contentLabel.font = [UIFont fontWithName:@"Helvetica" size:14];
    contentLabel.numberOfLines = 0;
    contentLabel.lineBreakMode = UILineBreakModeWordWrap;
    contentLabel.text = contentText;

我正在使用NIAttributedLabel,我认为这不会真正产生影响,因为返回我认为错误大小的方法是NSString 的一部分。

我确实在 Apple 的文档中读到过,该方法有时会截断字符串,尽管我认为这就是大高度约束的用途

编辑: 我发现这是NIAttributedLabel 的问题,如果我使用常规的 UILabel,它可以完美地工作。 这是两个源字符串和相应的屏幕截图,第一个演示我的问题,另一个决定没问题:

"Buying a Mobile\nHello - I'd like a Motorola Defy with a Smartphone 60 Plan.\nBroadband Problem\nMy Broadband’s out. I've tested the router and cables and ruled out my equipment. Is there a problem at your end?"

"Buying a Mobile\nI\'m Mrs Sina Manu-Harris. My account number is 156205169. I\'m going overseas in 6 months time on the 2nd of September and I\'d like to get organized in advance and buy a new mobile phone.\nBroadband Problem\nGood afternoon. It’s Mrs Sina Manu-Harris here. My account number is 156205169. My Broadband isn’t working. I’ve checked my network and phone cables and I've also checked my filters."

【问题讨论】:

  • 描述它是如何不工作的。截图会很有帮助。你有没有一步一步来看看标签的最终高度是否真的是sizeWithFont中确定的高度?也许在 NIAttributedLabel 实现中有一些怪癖。
  • 我什至有与 UILabel 类似的问题...

标签: ios nsstring nsattributedstring nimbus-ios


【解决方案1】:

NimbusKit 1.0 提供了一种计算 NIAttributedLabel 高度的新方法: NISizeOfAttributedStringConstrainedToSize()

我曾经使用 sizeWithFont: 并遇到与您相同的问题。 现在新方法对我很有效 (我的属性标签中没有任何图像)

【讨论】:

    【解决方案2】:

    您不能依赖 NSString 使用与 CoreText 相同的字形放置算法。在调整 NIAttributedLabel 大小时,建议您使用标签的 sizeToFitsizeThatFits: 方法,因为它们使用 CoreText 来确定标签的理想大小。

    【讨论】:

      【解决方案3】:

      请检查字符串@"T\nT\nT",它只会打印@"T\nT\n"。 _textFrame 似乎只显示两条可见线而不是三条。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-30
        • 1970-01-01
        相关资源
        最近更新 更多