8

我想用我设置的文本量以编程方式更改 UITextView,我有一个问题,如果我用界面生成器添加 UITextView 并且我这样做:

CGRect frame = textViewA1.frame;
frame.size.height = textViewA1.contentSize.height;
textViewA1.frame = frame;

一切正常,但如果我以编程方式创建 UITextView,高度不会改变,我这样做:

 UITextView *textViewA1 = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, 320, 50)];
[textViewA1 setFont:[UIFont fontWithName:@"Enriqueta" size:15]];
[textViewA1 setScrollEnabled:NO];
[textViewA1 setUserInteractionEnabled:NO];
[textViewA1 setBackgroundColor:[UIColor clearColor]];
[textViewA1 setText:@"A lot of text"];
CGRect frame = textViewA1.frame;
frame.size.height = textViewA1.contentSize.height;
textViewA1.frame = frame;

这样uitextview的高度大小不会改变,我该怎么办?

4

5 回答 5

10

只需将sizeToFit消息发送到UITextView. 它将调整自己的高度以适合其文本。它不会改变自己的宽度或原点。

[textViewA1 sizeToFit];
于 2012-06-29T00:39:32.427 回答
10

我认为你需要做:

CGRect frame = textViewA1.frame;
frame.size.height = textViewA1.contentSize.height;
textViewA1.frame = frame;

在添加子视图之后:

[self.view addSubview: self.textView];
于 2013-06-03T07:09:43.857 回答
0

您需要计算您拥有的文本的帧大小,例如:

UIFont *font = [UIFont fontWithName:@"Enriqueta" size:15];
NSString *text = @"A lot of text";
CGSize frameSize = [text sizeWithFont:font];
CGRect originalFrame = textViewA1.frame;
textViewA1.frame = CGRectMake(CGRectGetMinX(originalFrame), CGRectGetMinY(originalFrame), frameSize.width, frameSize.height);

为防止其超过特定高度,请使用:

CGFloat maxHeight = 100; // or something
CGSize frameSize = [text sizeWithFont:font constrainedToSize:maxHeight];
于 2012-06-28T23:35:50.407 回答
0

试试这个代码

UIFont * font = [UIFont fontWithName:@"Enriqueta" size:15];
textViewA1.font = font;
NSString * theText = @"A lot of text";
CGSize theStringSize = [theText sizeWithFont:font constrainedToSize:CGSizeMake(190, 1000000) lineBreakMode:UILineBreakModeWordWrap];
CGRect frame = textViewA1.frame;
frame.size.height = theStringSize.height;
textViewA1.frame = frame;

对于 textview,这当然具有 190 像素的静态宽度。你显然可以改变它!

于 2012-06-29T00:14:31.853 回答
-2

UITextView在 textview 中添加多行时滚动

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    CGRect frameTextView = textView.frame;
    frameTextView.height -= KEY_BOARD_HEIGHT;
    textView.frame = frameTextView;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView;
{
    CGRect frameTextView = textView.frame;
    frameTextView.height += KEY_BOARD_HEIGHT;
    textView.frame = frameTextView;
}
于 2012-11-20T04:19:23.383 回答