调整UITextView的大小

时间:2009-04-08 06:03:06

标签: iphone uitextview

我的UITextView添加了UIView。添加的textview不可编辑,只是显示一些数据。 textview中显示的数据是动态的。那是线数不固定。它可能会有所不同因此,如果行数增加,则还需要增加textview的大小。我不知道如何做到这一点。请给我一些想法。

更新

这就是我正在做的事情:

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

10 个答案:

答案 0 :(得分:58)

How do I size a UITextView to its content?

上发布了答案
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

或更好(考虑到内容感谢kpower的评论)

CGRect frame = _textView.frame;
UIEdgeInsets inset = textView.contentInset;
frame.size.height = _textView.contentSize.height + inset.top + inset.bottom;
_textView.frame = frame;

注意:如果要多次引用对象的属性(例如frame或contentInset),最好将其分配给局部变量,这样就不会触发额外的方法调用(_textView.frame / [_ textView frame是方法调用)。如果你经常调用这段代码(100000次),那么这将会明显变慢(十几个方法调用是无关紧要的)。

然而......如果你想在没有额外变量的一行中这样做,那就是

        _textView.frame = CGRectMake(_textView.frame.origin.x, _textView.frame.origin.y, _textView.frame.size.width, _textView.contentSize.height + _textView.contentInset.top + _textView.contentInset.bottom);

以5个额外的方法调用为代价。

答案 1 :(得分:29)

您可以使用setFrame:sizeToFit

<强>更新

我将sizeToFitUILabel一起使用,它运行正常,但UITextViewUIScrollView的子类,所以我可以理解为什么sizeToFit没有不会产生预期的结果。

您仍然可以计算文字高度并使用setFrame,但如果文字太长,您可能希望利用UITextView的滚动条。

以下是获得文字高度的方法:

#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

一起使用
[textView setFont:[UIFont systemFontOfSize:14]];
[textView setFrame:CGRectMake(5, 30, 100, size.height + 10)];

或者您可以先进行高度计算并避开setFrame行:

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(5, 30, 100, size.height + 10)];

答案 2 :(得分:2)

textView.contentSize.height中的

textViewDidChange只能在文本实际增长后调整大小。为了获得最佳视觉效果,请事先调整大小。几个小时之后,我已经想出如何使它与Instagram完全一样(它在所有BTW中具有最佳算法)

初始化:

    // Input
    _inputBackgroundView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, size.height - _InputBarHeight, size.width, _InputBarHeight)];
    _inputBackgroundView.autoresizingMask = UIViewAutoresizingNone;
   _inputBackgroundView.contentMode = UIViewContentModeScaleToFill;
    _inputBackgroundView.userInteractionEnabled = YES;
    [self addSubview:_inputBackgroundView];
   [_inputBackgroundView release];

   [_inputBackgroundView setImage:[[UIImage imageNamed:@"Footer_BG.png"] stretchableImageWithLeftCapWidth:80 topCapHeight:25]];

    // Text field
    _textField = [[UITextView alloc] initWithFrame:CGRectMake(70.0f, 0, 185, 0)];
   _textField.backgroundColor = [UIColor clearColor];
    _textField.delegate = self;
   _textField.contentInset = UIEdgeInsetsMake(-4, -2, -4, 0);
   _textField.showsVerticalScrollIndicator = NO;
   _textField.showsHorizontalScrollIndicator = NO;
    _textField.font = [UIFont systemFontOfSize:15.0f];
    [_inputBackgroundView addSubview:_textField];
   [_textField release];

   [self adjustTextInputHeightForText:@""];

填写UITextView委托方法:

- (void) textViewDidBeginEditing:(UITextView*)textView {

   [self adjustTextInputHeightForText:_textField.text];
}

- (void) textViewDidEndEditing:(UITextView*)textView {

   [self adjustTextInputHeightForText:_textField.text];
}

- (BOOL) textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text {

   if ([text isEqualToString:@"\n"])
   {
      [self performSelector:@selector(inputComplete:) withObject:nil afterDelay:.1];
      return NO;
   }
   else if (text.length > 0)
   {
      [self adjustTextInputHeightForText:[NSString stringWithFormat:@"%@%@", _textField.text, text]];
   }
   return YES;
}

- (void) textViewDidChange:(UITextView*)textView {

   [self adjustTextInputHeightForText:_textField.text];
}

诀窍是......

- (void) adjustTextInputHeightForText:(NSString*)text {

   int h1 = [text sizeWithFont:_textField.font].height;
   int h2 = [text sizeWithFont:_textField.font constrainedToSize:CGSizeMake(_textField.frame.size.width - 16, 170.0f) lineBreakMode:UILineBreakModeWordWrap].height;

   [UIView animateWithDuration:.1f animations:^
   {
      if (h2 == h1)
      {
         _inputBackgroundView.frame = CGRectMake(0.0f, self.frame.size.height - _InputBarHeight, self.frame.size.width, _InputBarHeight);
      }
      else
      {
         CGSize size = CGSizeMake(_textField.frame.size.width, h2 + 24);
         _inputBackgroundView.frame = CGRectMake(0.0f, self.frame.size.height - size.height, self.frame.size.width, size.height);
      }
      CGRect r = _textField.frame;
      r.origin.y = 12;
      r.size.height = _inputBackgroundView.frame.size.height - 18;
      _textField.frame = r;

   } completion:^(BOOL finished)
   {
      //
   }];
}

答案 3 :(得分:2)

sizeToFit是否有效

如果在第一次调整大小时设置文本后调用sizeToFit。因此,在第一次设置后,后续调用set text将导致大小没有变化。即使你调用sizeToFit。

但是,您可以强制它像这样调整大小:

  1. 设置文字。
  2. 将textView框架高度更改为CGFLOAT_MAX。
  3. 调用sizeToFit。

答案 4 :(得分:1)

这对我很有用:

    #define MAX_HEIGHT 2000     
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:14]
          constrainedToSize:CGSizeMake(100, MAX_HEIGHT)
              lineBreakMode:UILineBreakModeWordWrap];

    [textview setFont:[UIFont systemFontOfSize:14]];
    [textview setFrame:CGRectMake(45, 6, 100, size.height + 10)];
    textview.text = text;

答案 5 :(得分:0)

执行以下操作:

_textView.text = someText;
[_textView sizeToFit];
_textView.frame.height = _textView.contentSize.height;

答案 6 :(得分:0)

解决类似的问题我刚刚创建了一个基于自动布局的轻量级UITextView子类,它根据用户输入的大小自动增长和缩小,并且可以通过最大和最小高度进行约束 - 所有这些都没有一行代码

https://github.com/MatejBalantic/MBAutoGrowingTextView

答案 7 :(得分:0)

@Gabe给出的答案似乎在iOS7.1中不起作用,直到viewDidAppear之后。请参阅下面的测试。

更新:实际上,情况更复杂。如果在resizeTheTextView方法中指定textView.text,则在iOS7中,调整大小相当于只允许一行文本。真的很奇怪。

更新2:另见UITextView content size different in iOS7

更新3:请查看我最近使用的代码,了解我现在使用的内容。似乎可以完成这项工作。

#import "ViewController.h"

@interface ViewController ()
{
    UITextView *textView;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    textView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 200, 1)];
    [self.view addSubview:textView];
    CALayer *layer = textView.layer;
    layer.borderColor = [UIColor blackColor].CGColor;
    layer.borderWidth = 1;

    textView.text = @"hello world\n\n";

    // Calling the method directly, after the view is rendered, i.e., after viewDidAppear, works on both iOS6.1 and iOS7.1
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"Change size" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(resizeTheTextView) forControlEvents:UIControlEventTouchUpInside];
    [button sizeToFit];
    CGRect frame = button.frame;
    frame.origin.y = 400;
    button.frame = frame;
    [self.view addSubview:button];

    // Works on iOS6.1, but does not work on iOS7.1
    //[self resizeTheTextView];
}

- (void) viewWillAppear:(BOOL)animated
{
    // Does not work on iOS7.1, but does work on iOS6.1
    //[self resizeTheTextView];
}

- (void) viewDidAppear:(BOOL)animated
{
    // Does work on iOS6.1 and iOS7.1
    //[self resizeTheTextView];
}

- (void) resizeTheTextView
{
    NSLog(@"textView.frame.size.height: %f", textView.frame.size.height);

    NSLog(@"textView.contentSize.height: %f", textView.contentSize.height);

    // 5) From https://stackoverflow.com/questions/728704/resizing-uitextview
    CGRect frame = textView.frame;
    UIEdgeInsets inset = textView.contentInset;
    frame.size.height = textView.contentSize.height + inset.top + inset.bottom;
    textView.frame = frame;

    NSLog(@"inset.top: %f, inset.bottom: %f",  inset.top,  inset.bottom);

    NSLog(@"textView.frame.size.height: %f", textView.frame.size.height);

    NSLog(@"textView.contentSize.height: %f", textView.contentSize.height);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

UPDATE3:

if ([[UIDevice currentDevice] majorVersionNumber] < 7.0) {
    CGRect frame = _abstractTextView.frame;
    UIEdgeInsets inset = _abstractTextView.contentInset;
    frame.size.height = _abstractTextView.contentSize.height + inset.top + inset.bottom;
    _abstractTextView.frame = frame;
}
else {
    CGSize textViewSize = [_abstractTextView sizeThatFits:CGSizeMake(_abstractTextView.frame.size.width, FLT_MAX)];
    _abstractTextView.frameHeight = textViewSize.height;
}

答案 8 :(得分:0)

如果您在其上设置内容模式,则将UITextView添加到其父级后,它似乎会自动调整其大小。

这意味着您不需要手动计算高度并应用高度限制。它似乎工作!!在iPad上测试iOS7和iOS8。

e.g。

--
textView.contentMode = UIViewContentMode.Center;
--

如果有人能够解释为什么这样可行,那将非常感激..我在界面构建器中弄乱选项时偶然发现了它。

答案 9 :(得分:0)

只需将scrollEnabled设置为NO,或取消选中IB中滚动视图部分中的滚动已启用UITextView将自行调整大小。