optimization - Efficiently determine how much text can fit in a UILabel in IOS -


i have nsstring , want know how of string fit uilabel.

my code builds test string adding 1 character @ time original string. each time add character test new string see if fit label:

cgrect cuttextrect = [cuttext boundingrectwithsize:maximumlabelsize options:nsstringdrawinguseslinefragmentorigin attributes:stringattributes context:nil]; 

then compare height of rect height of label see if string overflowed.

this works, instruments shows me loop taking cpu time.

can think of or know of faster way this?

thanks!

while not prettiest:

- (nsstring *)stringforwidth:(cgfloat)width fullstring:(nsstring *)fullstring {     nsdictionary *attributes = @{nsfontattributename: label.font};      if ([fullstring sizewithattributes:attributes].width <= width)     {         return fullstring;     }      // might worth researching more regarding 'average' char size      cgfloat approxcharwidth = [@"n" sizewithattributes:attributes].width;      nsinteger approxnumofchars = (nsinteger)(width / approxcharwidth);      nsmutablestring *resultingstring = [nsmutablestring stringwithstring:[fullstring substringtoindex:approxnumofchars]];      cgfloat currentwidth = [resultingstring sizewithattributes:attributes].width;      if (currentwidth < width)     {         // try 'sqeeze' char.         while (currentwidth < width && approxnumofchars < fullstring.length)         {             approxnumofchars++;              [resultingstring appendstring:[fullstring substringwithrange:nsmakerange(approxnumofchars - 1, 1)]];              currentwidth = [resultingstring sizewithattributes:attributes].width;         }     }      // string might oversized     if (currentwidth > width)     {         while (currentwidth > width)         {             [resultingstring deletecharactersinrange:nsmakerange(resultingstring.length - 1, 1)];              currentwidth = [resultingstring sizewithattributes:attributes].width;         }     }      // if dealing uilabel, it's safer have smaller string 'equal',     // 'clipping wise'. otherwise, use '<=' or '>=' instead of '<' or '>'      return [nsstring stringwithstring:resultingstring]; } 

there couple of loops, each 1 'fine tuning' , should run small number of times.

one way improve efficiency better starting point calculating how many n's can fit in given width. i'm open suggestions that.

-edit:

regarding multiline label, once know given text width, can expect following text (if any) go next line.

in other words, getting 'text width' tricky part, 'width text' free.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -