Jak obliczyć wysokość NSAttributedString z podaną szerokością w iOS 6 [duplikat]

Możliwy duplikat:
Jak uzyskać wysokość dla NSAttributedString na stałej szerokości

Teraz NSAttributedString jest dostępny w iOS 6. Dla celów układu, chcę wiedzieć, jak obliczyć wymaganą wysokość NSAttributedString w stałej szerokości. Szukam czegoś, co jest równoważne - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size NSString, ale dla NSAttributedString.

Aby obliczyć wielkość rysunku NSAttributedStrings, istnieją dwie metody dostępne:

  1. - (CGSize)size nie może być użyty, ponieważ nie bierze pod uwagę żadnej szerokości.
  2. próbowałem - (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options context:(NSStringDrawingContext *)context, ale jakoś nie daje mi prawidłowej wysokości. Myślę, że metoda jest błędna. Jeśli uruchamiam poniższy kod, to daje mi bounding size: 572.324951, 19.000000 ignorowanie podanej szerokości 200. To powinno dać mi jakieś 100 wzrostu.
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
    NSDictionary *attributes = @{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:15], NSForegroundColorAttributeName : [UIColor blueColor]};
    [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"Attributed String\n" attributes:attributes]];
    [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"Attributed String\n" attributes:attributes]];
    [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"Attributed String\n" attributes:attributes]];
    [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"Attributed String\n" attributes:attributes]];
    [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"Attributed String\n" attributes:attributes]];

    CGRect frame = [attributedString boundingRectWithSize:CGSizeMake(200, 1000) options:0 context:nil];
    NSLog(@"bounding size: %f, %f", frame.size.width, frame.size.height);

Istnieją inne metody dostępne dla Mac OS X, ale nie dla iOS.

Author: Community, 2013-01-19

1 answers

Opcja 2 działa w systemie iOS z odpowiednimi parametrami.

NSAttributedString *attrStr = ... // your attributed string
CGFloat width = 300; // whatever your desired width is
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(width, 10000) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];

Bez odpowiednich wartości dla parametru options otrzymasz złą wysokość.

Wymagane jest również, aby attrStr zawierał atrybut font. Bez czcionki nie ma sposobu na prawidłowe obliczenie rozmiaru.

 160
Author: rmaddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-10 00:13:38