Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I wrote the following recursive method and public API to do this properly. The ugly fudge factor is the subject of <a href="https://stackoverflow.com/questions/1095545/string-length-with-given-font-to-fit-uitextview-2-the-return">this question</a>.</p> <pre><code>#define kFudgeFactor 15.0 #define kMaxFieldHeight 9999.0 // recursive method called by the main API -(NSString*) sizeStringToFit:(NSString*)aString min:(int)aMin max:(int)aMax { if ((aMax-aMin) &lt;= 1) { NSString* subString = [aString substringToIndex:aMin]; return subString; } int mean = (aMin + aMax)/2; NSString* subString = [aString substringToIndex:mean]; CGSize tallerSize = CGSizeMake(self.frame.size.width-kFudgeFactor,kMaxFieldHeight); CGSize stringSize = [subString sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap]; if (stringSize.height &lt;= self.frame.size.height) return [self sizeStringToFit:aString min:mean max:aMax]; // too small else return [self sizeStringToFit:aString min:aMin max:mean];// too big } -(NSString*)sizeStringToFit:(NSString*)aString { CGSize tallerSize = CGSizeMake(self.frame.size.width-kFudgeFactor,kMaxFieldHeight); CGSize stringSize = [aString sizeWithFont:self.font constrainedToSize:tallerSize lineBreakMode:UILineBreakModeWordWrap]; // if it fits, just return if (stringSize.height &lt; self.frame.size.height) return aString; // too big - call the recursive method to size it NSString* smallerString = [self sizeStringToFit:aString min:0 max:[aString length]]; return smallerString; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload