简体   繁体   中英

How can I get the width of a string of XYZ font in iOS Objective-C?

I have the following:

-(float)getLength:(NSString *)text
{
    UIFont *font = [UIFont fontWithName:@"Scurlock" size:20];
    CGSize size = [text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font, 
        NSFontAttributeName, nil]];
    return size.width;
}

This is generating a compile-time error: "No visible @interface for 'NSString' declares the selector 'sizeWithAttributes.'"

I've searched, and it looks like the message sizeWithAttributes is appropriate to get rendered dimensions to an NSString. However, Xcode seems to disagree.

Once a font is given, perhaps Verdana for development porpoises, how can/should I query a string's dimensions as they will be rendered?

Use NSAttributedString.

 - (CGFloat)widthOfString:(NSString *)string withFont:(NSFont *)font {
 NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil];
 return [[[NSAttributedString alloc] initWithString:string attributes:attributes] size].width;
}

Answer from here .

try this

Some predefine values

    #define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 0.0f 



NSString *text = @"abcdefghijklmnopqrstuvwxyz";
    CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
    CGSize size = [text sizeWithFont:[UIFont fontWithName:@"XYZ" size:@"12"] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = MAX(size.height+30, 38.0f);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM