문제

I've gone over what feels like every post about this method on SO. And a lot of the posters answers are to just put a really large value as the height constraint.

However, for me this is not working. This is my code:

//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;

I am using NIAttributedLabel, thought this shouldn't really have an effect because the method returning what I believe to be the wrong size is part of NSString.

I did read in Apple's documentation that the method will truncate the string sometimes, though I thought thats what the large height constraint was for

EDIT: I've discovered that it is an issue with NIAttributedLabel, If I use a regular UILabel it works perfectly. Here are two source strings and corresponding screenshots, the first demonstrating my issue, the other deciding to be fine:

"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

도움이 되었습니까?

해결책

You can't depend on NSString using the same glyph placement algorithm that CoreText will. When sizing NIAttributedLabel it is recommended that you use the label's sizeToFit and sizeThatFits: methods because they use CoreText to determine the ideal size of the label.

다른 팁

NimbusKit 1.0 provide a new method for calculating height of NIAttributedLabel: NISizeOfAttributedStringConstrainedToSize()

I used to use sizeWithFont: and encounter same problem as you. Now the new method worked for me perfectly (I don't have any images in my attriubited label)

Please check with string @"T\nT\nT", it will only prints @"T\nT\n". It seems _textFrame only shows two visible lines instead of three.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top