iosobjective-cnsstringfontmetricssizewithfont

Calculating the CGSize of an unknown NSString


How can I find the CGSize of an unknown string that I just know its maximum number of characters but not the exact string?

I know that you can calculate the size of an specific NSString with the "sizeWithFont" method on NSString like this :

UIFont * font = [UIFont systemFontOfSize:15];
CGSize stringSize = [aString sizeWithFont:font]; 
CGFloat width = stringSize.width;

but I'm looking for a way when you don't know the exact string and just know the number of characters that the string may have.


Solution

  • The CGSize can only be estimated when you don't know the exact characters of the string. A worst-case estimation would possibly be to fill the whole string with "M" or "W" characters, cause I think this should be widest char in most fonts:

    int charCount = 10;
    NSString *testString = @"";
    for (int i = 0; i < charCount; i++) {
        testString = [testString stringByAppendingString:@"M"];
    }
    

    You could also estimate the best-case by adding "i"-chars. You should do a lot of testing to find the character that results best in most cases.