0

I'm creating one long string from a number of strings in an array like this:

oneString = @"First Line\n";
for (int i = 0; i < itemsToAdd.count; i ++){
    oneString = [NSString stringWithFormat:@"%@   %@\n", oneString, stringToAdd];
}

This all works great until stringToAdd is long enough to wrap. If you notice the spaces between %@ %@, this is acting as an indentation. Most of the strings I'm adding don't wrap, but I'm trying to figure out a way to add spaces before each line after the first.

The reason I'm building up this one long string is to calculate the height of it in order to adjust the size of a tableViewCell based on the length of this string. itemsToAdd is a variable size array. Sometimes it will be one line, sometimes it will be 15+ items.

This is sample output:

First Line
   Item 1 is good
   Item 2 is fine
   Item 3 is long and it wraps so
it goes like this and it sucks
   Item 4 is fine
Mike Z
  • 4,121
  • 2
  • 31
  • 53
  • Not a direct answer to your question, but why don't you just use the NSString's method sizeWithFont to calculate the width and height of the text when it's rendered? You could restrict the width to be less the four spaces that you try to add and it will tell you the exact amount of lines after indenting. Like in this post: http://stackoverflow.com/questions/4965809/how-to-use-nsstrings-sizewithfont-and-drawinrect-to-workout-how-much-of-a-strin – Greg May 25 '13 at 23:47
  • There's another loop I left out. `First Line` (the non-indented portion), has multiple possible values such as `Second Line` which would then have a variable number of items just like `First Line` has. So it's kind of printing an array (A) of arrays (B) with both the length of A and B unknown to start. – Mike Z May 26 '13 at 01:13
  • Instead for (int i = 0; i < itemsToAdd.count; i ++) you mean for (NSString* stringToAdd in itemsToAdd) probably? – stosha May 26 '13 at 01:21
  • I'm simplifying my loops because they aren't an issue. The sole issue is the indentation. – Mike Z May 26 '13 at 01:38

2 Answers2

0

Try like this for insert tab space:

oneString = [NSString stringWithFormat:@"%@%8s\n", oneString, [stringToAdd UTF8String]];

from how to add tab space into UILabel.text

Community
  • 1
  • 1
stosha
  • 2,108
  • 2
  • 27
  • 29
0

You need to specify the indent in a way understood by the text rendering system, for example, by using NSParagraphStyle. You will need to make some changes to your cells depending on which versions of iOS your app supports. You may want to use a 3rd party label class or a framework like DTCoreText.

Wain
  • 118,658
  • 15
  • 128
  • 151