22

I'm planning on loading multi-paragraph content from a text file and displaying it on the UI. I'll be loading from one of several text files and won't know ahead of time how long the text is going to be. My first thought was to use a UILabel inside a UIScrollView. However, it doesn't seem like UILabel can be made to expand based on the number of lines it contains. Is this correct?

If UILabel isn't the right tool for the job, what should I use? UIWebView? Will UIWebView handle the scrolling nicely for me?

morgancodes
  • 25,055
  • 38
  • 135
  • 187

2 Answers2

20

Check out UITextView. You can place one inside a UIView, and the text view provides all the functionality of a scroll view, and more (it is a UIScrollView subsclas).

Mark Granoff
  • 16,878
  • 2
  • 59
  • 61
14

If you don't want to use a UITextView, which is scrollable so will accommodate whatever text you need, you can check out some methods to compute the size of a UILabel, for example, on the fly.

This should get you started in the right direction: NSString has a few UIKit category methods

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size;
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode;

You call these methods on an NSString, passing in whatever font you want used as well as the maximum size. Usually, I will constrain the width but give a very large height so it can let me know what the best height is. These methods will return a CGSize that you can then use to set the frames of the UILabels. For example, if I know the maximum width that I can place the label in is 300 points wide, I will pass a CGSizeMake(300, 2000) for the constrained size.

Christian
  • 1,714
  • 8
  • 9