0

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?

Christos Hayward
  • 5,777
  • 17
  • 58
  • 113
  • 1
    I'm using a NSString category. Please look at this http://stackoverflow.com/questions/19010207/nsstring-sizewithfont-alternative-in-ios7/19010369#19010369 – matthias Sep 26 '13 at 11:14
  • sizeWithAttributes: is available from iOS7 only. Sure u don't have that issue running on iOS6? – DennyLou Feb 20 '14 at 14:40

2 Answers2

0

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.

Community
  • 1
  • 1
Tomasz Bąk
  • 6,124
  • 3
  • 34
  • 48
0

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);
Jignesh B
  • 490
  • 7
  • 18