• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Algorithm for fitting a string in a given width
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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.

  • Prev by Date: NSDictionary question
  • Next by Date: [NSApp deactivate]; isn't working...
  • Previous by thread: Re: NSDictionary question
  • Next by thread: [NSApp deactivate]; isn't working...
  • Index(es):
    • Date
    • Thread