简体   繁体   中英

Best way to add a large chunk of text to a UIScrollView?

What is the best way to display a large chunk of text (taken from a .txt file in the app) in a UIScrollView so a user can scroll about it? Length of the text is variable.

On Interface Builder open the Attributes Inspector (if not already open - command-1) and uncheck "Editable".

Also notice there's a Scroll View section below. Make sure "Scrolling" is checked.

Hope this helps somebody (the post is a year old so I guess by now the one who posted it doesn't need this info).

One way I had working for me is to create UILabel, set text and then set content size of scrollview by it size. Here is an example

Quote:

// alocate and initialize scroll
 UIScrollView *myScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];
 // alocate and initialize label
 UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];   

// add long text to label
 myLabel.text = @"Lorem ipsum... long text here";
 // set line break mode to word wrap
 myLabel.lineBreakMode = UILineBreakModeWordWrap;
 // set number of lines to zero
 myLabel.numberOfLines = 0;
 // resize label
 [myLabel sizeToFit];

// set scroll view size
 myScroll.contentSize = CGSizeMake(myScroll.contentSize.width, myLabel.frame.size.height);
 // add myLabel
 [myScroll addSubview:myLabel];
 // add scroll view to main view
 [self.view addSubview:myScroll];

I came here looking for an answer and found that all answers are bad - or flat out wrong.

The proper way to do this is using UITextView by itself. Since it is a descendant of UIScrollView, it has scrolling built-in and lots of features for adjusting formatting such as the insets etc.

If you intend to only show text, you need to explicitly disable editing. You do this by setting the "editable" property to false. And if you want to disable the text selection mechanism, set the "selectable" property to false.

In newer versions of iOS, UITextView has added support for NSTextContainer which gives you even greater control over formatting.

Usage of the UITextView into the UIScrollView. I could not recommend this because UITextView is the subclass of UIScrollView. Apple is also recommending the same.

Use UILabel in this case as a sub-view,

将UITextView放入UIScrollView。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM