Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate an NSString to fit a size? [duplicate]

Possible Duplicate:
Measuring the pixel width of a string in Objective C

I use the [string drawInRect:] methods, and would like the string to be truncated to the maximum length that would fit in that size. It's not as simple as finding out how many characters there are per line, as every letter is a different width. The reason I want to find where the string is no longer visible is so I can add elipses onto the end of the string.

like image 720
Andrew Avatar asked Jan 10 '13 23:01

Andrew


2 Answers

Look at the documentation of drawInRect:withAttributes: in the NSString Additions Reference. Under "Constants" you will find an option that does what you want automatically:

NSStringDrawingTruncatesLastVisibleLine Truncates and adds the ellipsis character to the last visible line if the text doesn't fit into the bounds specified.

like image 119
Mundi Avatar answered Sep 20 '22 21:09

Mundi


You can use if the solution given by @Mundi are insufficient or you need to know how much text fit.

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size

in a loop decreasing the size of the text until it fits.

like image 37
zaph Avatar answered Sep 20 '22 21:09

zaph