调整UITextView的大小 [英] Resizing UITextView
问题描述
我在UIView
上添加了UITextView
.添加的textview不可编辑,仅用于显示一些数据.文本视图中显示的数据是动态的.多数民众赞成在行数不是固定的.可能会有所不同.因此,如果增加行数,则文本视图的大小也需要增加.我不知道该怎么做.请给我一些想法.
I have a UITextView
added on my UIView
. The textview added is not editable, it is just to display some data. The data displayed in the textview is dynamic. Thats is the number of lines is not fixed. It may vary. So if the number of line increases, the size of the textview also needs to be increased. I have no clue how to do this. Please give me some ideas.
更新:
这是我在做什么:
UIView *baseView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
baseView.backgroundColor = [UIColor grayColor];
[window addSubview:baseView];
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(5, 30, 100, 30)];
textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
textView.text = @"asdf askjalskjalksjlakjslkasj";
[textView sizeToFit];
[baseView addSubview:textView];
推荐答案
您可以使用setFrame:
或sizeToFit
.
更新:
我将sizeToFit
与UILabel
一起使用,并且效果很好,但是UITextView
是UIScrollView
的子类,因此我可以理解为什么sizeToFit
不能产生期望的结果.
I use sizeToFit
with UILabel
, and it works just fine, but UITextView
is a subclass of UIScrollView
, so I can understand why sizeToFit
doesn't produce the desired result.
您仍然可以计算文本高度并使用setFrame
,但是如果文本太长,您可能想利用UITextView
的滚动条.
You can still calculate the text height and use setFrame
, but you might want to take advantage of UITextView
's scrollbars if the text is too long.
以下是获取文字高度的方法:
Here's how you get the text height:
#define MAX_HEIGHT 2000
NSString *foo = @"Lorem ipsum dolor sit amet.";
CGSize size = [foo sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:CGSizeMake(100, MAX_HEIGHT)
lineBreakMode:UILineBreakModeWordWrap];
,然后可以将其与UITextView
一起使用:
and then you can use this with your UITextView
:
[textView setFont:[UIFont systemFontOfSize:14]];
[textView setFrame:CGRectMake(5, 30, 100, size.height + 10)];
或者您可以先进行高度计算并避开setFrame
行:
or you can do the height calculation first and avoid the setFrame
line:
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(5, 30, 100, size.height + 10)];
这篇关于调整UITextView的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!