如何使用NIAttributedLabel正确使用NSString sizeWithFont constratinedToSize

时间:2012-07-13 07:54:42

标签: ios nsstring nsattributedstring nimbus-ios

我已经在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的一部分。 < / p> <击>

我确实在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?"

Screenshot 1

"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."

Screenshot 2

3 个答案:

答案 0 :(得分:1)

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

我曾经使用sizeWithFont:遇到和你一样的问题。 现在,这种新方法对我来说非常有用 (我的attriubited标签上没有任何图像)

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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