3

なぜこれが機能しないのですか?文字列の長さに関係なく、常に18を返します。このスレッドはありますが、決定的な答えではありません。

    NSString * t = @"<insert super super long string here>";

    CGSize size = [t sizeWithFont:[UIFont systemFontOfSize:14.0] forWidth:285 lineBreakMode:UILineBreakModeWordWrap];

    NSLog(@"size.height is %f and text is %@", size.height, t);

ありがとう、

トッド

4

3 に答える 3

5

sizeWithFont:constrainedToSize:lineBreakMode:代わりに使用してください。

NSString * t = @"<insert super super long string here>";
CGSize constrainSize = CGSizeMake(285, MAXFLOAT);
CGSize size = [t sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:constrainSize lineBreakMode:UILineBreakModeWordWrap];
NSLog(@"size.height is %f and text is %@", size.height, t);
于 2012-09-05T03:03:43.177 に答える
1

非推奨のメソッド:NS_DEPRECATED_IOS(2_0、7_0)

- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:");

CGSize titleTextSize = [self.titleLabel.text sizeWithFont:self.myLabel.font forWidth:myLabelWidth lineBreakMode:NSLineBreakByTruncatingTail];

新しいアプローチ

使用する :

- (CGRect)boundingRectWithSize:(CGSize)size
                       options:(NSStringDrawingOptions)options
                    attributes:(NSDictionary<NSString *,
                                        id> *)attributes
                       context:(NSStringDrawingContext *)context

例:

 // Create a paragraph style with the desired line break mode
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;

    // Create the attributes dictionary with the font and paragraph style
    NSDictionary *attributes = @{
                                 NSFontAttributeName:self.myLabel.font,
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };

    // Call boundingRectWithSize:options:attributes:context for the string
    CGRect textRect = [self.countLabel.text boundingRectWithSize:CGSizeMake(widthOfMyLabel, 999999.0f)
                                           options:NSStringDrawingUsesLineFragmentOrigin
                                        attributes:attributes
                                           context:nil];

ApppleDocを参照してください

于 2015-11-30T06:17:52.143 に答える
0
CGSize size = [t sizeWithFont:[UIFont fontWithName:@"Arial-BoldMT" size:16.0] constrainedToSize:CGSizeMake(220,500) lineBreakMode:UILineBreakModeWordWrap];
于 2012-09-05T07:56:14.223 に答える