Eyal
Eyal

Reputation: 10828

Objective c - Text indentation

This question is about implementing text indentation ("The placement of text farther to the right to separate it from surrounding text") in iOS.

Take for example the following text:

  1. This is the first section.
  2. This is the second one,
    with two lines.
  3. This is the third.

Notice that the second row in section 2 begin farther to the right and just below the line above.

My code contains an array of NSString, each one should be display as a section with numeric bullet like above. for example:

NSArray *array = [NSArray arrayWithObjects:@"1. This is the first section.", @"2. This is the second one, with two lines.", @"3. This is the third.", nil];

I use UILable to display the text on screen.
To set the text from the array to the label, and to separate each string in a new line I use

myLabel.text = [array componentsJoinedByString:@"\n"];

Any ideas how to get this effect?

Upvotes: 10

Views: 6744

Answers (3)

Eyal
Eyal

Reputation: 10828

Well I decided to implement it my self without using Core Text, I just created a view strcture that make all the indentation work by itself, and let you customize it as you want.

For all of you interested in the implementation, you can see the source code and an example project here:
ECListView Project

Upvotes: 2

Brian Nickel
Brian Nickel

Reputation: 27560

This is possible to some degree in iOS6 with - [UILabel setAttributedText:].

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.headIndent = 29;

myLabel.attributedText = [[NSAttributedString alloc] initWithString:
    @"1.\tShort line.\n2.\tLong line with content that triggers wrapping.\n3.\tShort line."
    attributes:@{NSParagraphStyleAttributeName: paragraphStyle}];

Result of the above code

This adds indentation to the subsequent lines. It looks like iOS doesn't support tab stops in the same way as OSX so I'm not seeing a way to adjust the gap between the number and the text. This is probably possible in CoreText.

Of course, you could also just replace the label with a UIWebView and have full formatting control on all versions of iOS at the cost of performance.

Upvotes: 26

Caleb
Caleb

Reputation: 125007

UILabel is not going to cut it if you have any kind of specific layout requirements. For that, you're going to need to dig into Core Text. The good news is that Core Text will let you do any kind of text layout you can imagine. The bad news is that all that power brings with it some complexity, so to use it you're going to have to invest some time learning how the framework works.

An alternative that's suitable in some situations is to use a web view to display your text. UIWebView will let you do whatever text layout you can manage using HTML and CSS.

Upvotes: 0

Related Questions