6

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.

Community
  • 1
  • 1
Andrew
  • 15,935
  • 28
  • 121
  • 203
  • 1
    The question marked as a duplicate explains how to measure an NSString, not how to truncate it. – picciano Apr 20 '15 at 22:28
  • 1
    Here is a way to do this: `- (NSString *)stringByTruncatingToWidth:(CGFloat)width attributes:(NSDictionary *)textFontAttributes { CGSize size = [self sizeWithAttributes:textFontAttributes]; if (size.width <= width) { return self; } for (int i = 2; i < self.length; i++) { NSString *testString = [NSString stringWithFormat:@"%@…", [self substringToIndex:self.length - i]]; CGSize size = [testString sizeWithAttributes:textFontAttributes]; if (size.width <= width) { return testString; } } return @""; }` – picciano Apr 20 '15 at 22:36

3 Answers3

2

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.

Mundi
  • 79,884
  • 17
  • 117
  • 140
1

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.

zaph
  • 111,848
  • 21
  • 189
  • 228
0

Where do you want to use this string? If it's in a UILabel, you can use NSLineBreakMode = NSLineBreakByTruncatingTail.

Jacek Lampart
  • 1,741
  • 13
  • 25