How to create a UITextView that automatically wraps lines of text?
I am creating an app that creates a UITextView programmatically. The problem is, when the user 开发者_StackOverflow中文版types in text or the app sets the text, the words spread across one line and off the screen, rather than wrapping to the next line. When I create a UITextView with interface builder, the text wraps automatically, but not when it is created programmatically.
Code:
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 12, 210, 60)];
[[self view] addSubview:textView];
[textView becomeFirstResponder];
Available since iOS 7:
textView.textContainer.lineBreakMode = NSLineBreakByWordWrapping;
UITextView
and UITextField
are different classes. UITextField
is single line and UITextView
is multiline. Create a UITextView
rather than a UITextField
programmatically and you have solved your problem I expect.
The entire point of UITextView
is to allow multiple lines of text. From the documentation:
The
UITextView
class implements the behavior for a scrollable, multiline text region. The class supports the display of text using a custom font, color, and alignment and also supports text editing. You typically use a text view to display multiple lines of text, such as when displaying the body of a large text document.
Since UITextView
inherits from UIScrollView
, you may be able to force it to cooperate by disabling the horizontal scrolling. To do this, you want to set the contentSize
, e.g.
CGSize scrollableSize = CGSizeMake(210, 480);
[textView setContentSize:scrollableSize];
This will fix the width to 210
and allow the height to scroll to 480
. Since you are setting the textView
to size (210,60)
, this should allow the vertical scrolling but not the horizontal scrolling.
精彩评论