Question

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.

Was it helpful?

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.

OTHER TIPS

I don't think there would be a way.

Why it is required to pass a string?

  • Because its the letters which consumes width and those gets changes as per selected font. Like, 'lll' will cover lesser space than 'HHH', although both contains same number of letters (here its 3). Hence its mandatory to provide characters.

Work-around for this

  • Provide a letter which consumes maximum width like H, Q, W, etc. and pass how many letters are there. For ex.: If you require width for 5 letters then execute statement like below:
UIFont * font = [UIFont systemFontOfSize:15];

CGSize stringSize = [@"WWWWW"sizeWithFont:font]; // 5 times 'W'

CGFloat width = stringSize.width;

Now you will get maximum width probability, which allows all the other string probabilities.

This is just a work-around, I don't think there is an exact solution available in iOS SDK.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top