Algorithm for fitting a string in a given width
Algorithm for fitting a string in a given width
- Subject: Algorithm for fitting a string in a given width
- From: Greg Hulands <email@hidden>
- Date: Fri, 4 Jul 2003 13:21:15 +1000
Here is an algorithm to fit a string into a given width. If it is too
long it puts ellipses in the middle. I'm sure someone will find a use
for it.
Greg
- (NSString *)elipsedStringFromString:(NSString *)string
forAttributes:(NSDictionary *)attributes
maximumWidth:(float)width
{
unsigned length = [string length];
unsigned mid = length / 2;
NSString *s1, *s2, *newString;
NSSize size = [string sizeWithAttributes:attributes];
//see if we need to actually add ellipses
if (size.width <= width)
return string;
s1 = [string substringToIndex:mid];
s2 = [string substringFromIndex:mid];
while (size.width > width)
{
s1 = [s1 substringToIndex:[s1 length] - 1];
s2 = [s2 substringFromIndex:1];
newString = [NSString stringWithFormat:@"%@...%@", s1, s2];
size = [newString sizeWithAttributes:attributes];
}
return newString;
}
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.