开发者

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

开发者 https://www.devze.com 2022-12-23 21:01 出处:网络
What is the best way to display a large chunk of text (taken from a开发者_JAVA百科 .txt file in the app) in a UIScrollView so a user can scroll about it? Length of the text is variable.On Interface Bu

What is the best way to display a large chunk of text (taken from a开发者_JAVA百科 .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).


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.


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];


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,


Put the UITextView into the UIScrollView.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号