¿Cómo puedo ajustar el tamaño de un UITextView a su contenido?


¿hay una buena manera de ajustar el tamaño de un UITextView para ajustarse a su contenido? Digamos por ejemplo que tengo un UITextView que contiene una línea de texto:

"Hello world"

Luego agrego otra línea de texto:

"Goodbye world"

¿Hay una buena manera en Cocoa Touch de obtener el rect que mantendrá todas las líneas en la vista de texto para que pueda ajustar la vista padre en consecuencia?

Como otro ejemplo, mire el campo de notas para eventos en la aplicación de calendario-observe cómo la celda (y el UITextView contiene) se expande para mantener todas las líneas de texto en la cadena de notas.

Author: Alok, 2008-09-08

30 answers

Esto funciona tanto para iOS 6.1 como para iOS 7:

- (void)textViewDidChange:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    textView.frame = newFrame;
}

O en Swift (Funciona con Swift 4.1 en iOS 11)

let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)

Si desea soporte para iOS 6.1, también debe:

textview.scrollEnabled = NO;
 542
Author: jhibberd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-12 23:46:14

Esto ya no funciona en iOS 7 o superior

En realidad hay una manera muy fácil de cambiar el tamaño de la UITextView a su altura correcta del contenido. Se puede hacer usando el UITextView contentSize.

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

Una cosa a tener en cuenta es que el contentSize correcto solo está disponible después de el UITextView se ha agregado a la vista con addSubview. Antes de eso es igual a frame.size

Esto no funcionará si el diseño automático está ACTIVADO. Con auto layout, el enfoque general es usar el sizeThatFits método y actualizar el valor constant en una restricción de altura.

CGSize sizeThatShouldFitTheContent = [_textView sizeThatFits:_textView.frame.size];
heightConstraint.constant = sizeThatShouldFitTheContent.height;

heightConstraint es una restricción de diseño que normalmente configura a través de un IBOutlet al vincular la propiedad a la restricción de altura creada en un guion gráfico.


Solo para añadir a esta increíble respuesta, 2014, si:

[self.textView sizeToFit];

Hay una diferencia en el comportamiento con el iPhone6+ solo:

introduzca la descripción de la imagen aquí

Con el 6+ solamente (no los 5s o 6) agrega "una línea más en blanco" al UITextView. La" solución RL " soluciona esto perfectamente:

CGRect _f = self.mainPostText.frame;
_f.size.height = self.mainPostText.contentSize.height;
self.mainPostText.frame = _f;

Soluciona el problema de "línea extra" en 6+.

 570
Author: Ronnie Liew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-29 10:37:59

Para hacer un dimensionamiento dinámico UITextView dentro de un UITableViewCell, encontré que la siguiente combinación funciona en Xcode 6 con el SDK de iOS 8:

  • Añadir un UITextView a a UITableViewCell y restringir a los lados
  • Establezca la propiedad UITextView's scrollEnabled en NO. Con el desplazamiento activado, el marco del UITextView es independiente de su tamaño de contenido, pero con el desplazamiento desactivado, hay una relación entre los dos.
  • Si su tabla está utilizando la altura de fila predeterminada original de 44, entonces calculará automáticamente las alturas de fila, pero si cambió la altura de fila predeterminada a otra cosa, es posible que deba activar manualmente el cálculo automático de las alturas de fila en viewDidLoad:

    tableView.estimatedRowHeight = 150;
    tableView.rowHeight = UITableViewAutomaticDimension;
    

Para dimensionar dinámicamente UITextViews de solo lectura, eso es todo. Si estás permitiendo a los usuarios editar el texto en tu UITextView, también necesitas:

  • Implementa el método textViewDidChange: del protocolo UITextViewDelegate, y dile a tableView que se vuelva a pintar cada vez que el texto sea editado:

    - (void)textViewDidChange:(UITextView *)textView;
    {
        [tableView beginUpdates];
        [tableView endUpdates];
    }
    
  • Y no se olvide de establecer el delegado UITextView en algún lugar, ya sea en Storyboard o en tableView:cellForRowAtIndexPath:

 85
Author: Brett Donald,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-28 08:37:42

Swift :

textView.sizeToFit()
 53
Author: Juan Boero,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-24 21:43:42

Solo establece

Por Código

textView.scrollEnabled = false

Por Storyboard

introduzca la descripción de la imagen aquí

No hay necesidad de hacer nada aparte de esto.

 35
Author: Alok,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-29 08:34:28

En mi (limitada) experiencia,

- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode

No respeta los caracteres de nueva línea, por lo que puede terminar con CGSize mucho más corto de lo que realmente se requiere.

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size

Parece respetar las nuevas líneas.

Además, el texto no se representa realmente en la parte superior de la UITextView. En mi código, establecí la nueva altura de UITextView para que sea 24 píxeles más grande que la altura devuelta por los métodos sizeOfFont.

 24
Author: user63934,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-01 12:47:24

En iOS6, puede verificar la propiedad contentSize de UITextView justo después de configurar el texto. En iOS7, esto ya no funcionará. Si desea restaurar este comportamiento para iOS7, coloque el siguiente código en una subclase de UITextView.

- (void)setText:(NSString *)text
{
    [super setText:text];

    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        CGRect rect = [self.textContainer.layoutManager usedRectForTextContainer:self.textContainer];
        UIEdgeInsets inset = self.textContainerInset;
        self.contentSize = UIEdgeInsetsInsetRect(rect, inset).size;
    }
}
 22
Author: phatmann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-12 22:19:34

Publicaré la solución correcta en la parte inferior de la página en caso de que alguien sea valiente (o lo suficientemente desesperado) para leer hasta este punto.

Aquí está el repositorio de GitHub para aquellos que no quieren leer todo ese texto: resizableTextView

Esto funciona con iOS7 (y creo que funcionará con iOs8) y con autolayout. No necesitas números mágicos, desactivar el diseño y cosas así. Solución corta y elegante.

Creo que todas las restricciones relacionadas el código debe ir al método updateConstraints. Por lo tanto, vamos a hacer nuestro propio ResizableTextView.

El primer problema que encontramos aquí es que no sabemos el tamaño real del contenido antes del método viewDidLoad. Podemos tomar un camino largo y con errores y calcularlo en función del tamaño de la fuente, los saltos de línea, etc. Pero necesitamos una solución robusta, así que haremos:

CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];

Así que ahora sabemos real contentSize no importa dónde estemos: antes o después viewDidLoad. Ahora agregue restricción de altura en TextView (a través de storyboard o código, sin importar cómo). Nos ajustaremos ese valor con nuestro contentSize.height:

[self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
    if (constraint.firstAttribute == NSLayoutAttributeHeight) {
        constraint.constant = contentSize.height;
        *stop = YES;
    }
}];

Lo último que hay que hacer es decirle a la superclase updateConstraints.

[super updateConstraints];

Ahora nuestra clase se ve como:

ResizableTextView.m

- (void) updateConstraints {
    CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];

    [self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
        if (constraint.firstAttribute == NSLayoutAttributeHeight) {
            constraint.constant = contentSize.height;
            *stop = YES;
        }
    }];

    [super updateConstraints];
}

Bonito y limpio, ¿verdad? ¡Y no tienes que lidiar con ese código en tus controladores!

Pero espera! Y NO HAY ANIMACIÓN!

Puede animar fácilmente los cambios para que textView se extiendan suavemente. He aquí un ejemplo:

    [self.view layoutIfNeeded];
    // do your own text change here.
    self.infoTextView.text = [NSString stringWithFormat:@"%@, %@", self.infoTextView.text, self.infoTextView.text];
    [self.infoTextView setNeedsUpdateConstraints];
    [self.infoTextView updateConstraintsIfNeeded];
    [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
        [self.view layoutIfNeeded];
    } completion:nil];
 18
Author: Nikita Took,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-25 07:43:39

¿Intentaste [textView sizeThatFits:textView.bounds]?

Edit: sizeThatFits devuelve el tamaño pero en realidad no redimensiona el componente. No estoy seguro si eso es lo que quieres, o si [textView sizeToFit] es más lo que estabas buscando. En cualquier caso, no sé si se ajustará perfectamente al contenido que deseas, pero es lo primero que debes probar.

 12
Author: Mike McMaster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-08 20:45:44

Otro método es encontrar el tamaño que tomará una cadena en particular usando el método NSString:

-(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size

Esto devuelve el tamaño del rectángulo que se ajusta a la cadena dada con la fuente dada. Pase un tamaño con el ancho deseado y una altura máxima, y luego puede mirar la altura devuelta para ajustarse al texto. Hay una versión que le permite especificar el modo de salto de línea también.

Luego puede usar el tamaño devuelto para cambiar el tamaño de su vista para que se ajuste.

 9
Author: Code Addict,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-01 12:47:40

Si no tiene el UITextView a mano (por ejemplo, está dimensionando las celdas de la vista de tabla), tendrá que calcular el tamaño midiendo la cadena, luego teniendo en cuenta los 8 pt de relleno a cada lado de un UITextView. Por ejemplo, si conoce el ancho deseado de su vista de texto y desea averiguar la altura correspondiente:

NSString * string = ...;
CGFloat textViewWidth = ...;
UIFont * font = ...;

CGSize size = CGSizeMake(textViewWidth - 8 - 8, 100000);
size.height = [string sizeWithFont:font constrainedToSize:size].height + 8 + 8;

Aquí, cada 8 representa uno de los cuatro bordes acolchados, y 100000 solo sirve como un tamaño máximo muy grande.

En la práctica, es posible que desee agregar un font.leading extra a la altura; esto agrega una línea en blanco debajo de su texto, que puede verse mejor si hay controles visualmente pesados directamente debajo de la vista de texto.

 8
Author: Brent Royal-Gordon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-01 12:48:03

Las siguientes cosas son suficientes:

  1. Solo recuerde establecer desplazamiento habilitado a NO {[7] } para su UITextView:

introduzca la descripción de la imagen aquí

  1. Establezca correctamente las Restricciones de Diseño automático.

Incluso puedes usar UITableViewAutomaticDimension.

 7
Author: Bartłomiej Semańczyk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-02 10:18:23

Podemos hacerlo por restricciones .

  1. Establezca restricciones de altura para UITextView. introduzca la descripción de la imagen aquí

2.Cree IBOutlet para esa restricción de altura.

 @property (weak, nonatomic) IBOutlet NSLayoutConstraint *txtheightconstraints;

3.no olvides configurar delegate para tu textview.

4.

-(void)textViewDidChange:(UITextView *)textView
{
    CGFloat fixedWidth = textView.frame.size.width;
    CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
    CGRect newFrame = textView.frame;
    newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
    NSLog(@"this is updating height%@",NSStringFromCGSize(newFrame.size));
    [UIView animateWithDuration:0.2 animations:^{
                  _txtheightconstraints.constant=newFrame.size.height;
    }];

}

Luego actualice su restricción de esta manera:)

 7
Author: Kishore Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-04 07:16:20

Combinado con la respuesta de Mike McMaster, es posible que desee hacer algo como:

[myTextView setDelegate: self];

...

- (void)textViewDidChange:(UITextView *)textView {
  if (myTextView == textView) {
     // it changed.  Do resizing here.
  }
}
 6
Author: Olie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-06 04:31:12

Encontré una manera de cambiar el tamaño de la altura de un campo de texto de acuerdo con el texto dentro de él y también organizar una etiqueta debajo de él en función de la altura del campo de texto! Aquí está el código.

UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 10)];
NSString *str = @"This is a test text view to check the auto increment of height of a text view. This is only a test. The real data is something different.";
_textView.text = str;

[self.view addSubview:_textView];
CGRect frame = _textView.frame;
frame.size.height = _textView.contentSize.height;
_textView.frame = frame;

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 5 + frame.origin.y + frame.size.height, 300, 20)];
lbl.text = @"Hello!";
[self.view addSubview:lbl];
 6
Author: dheeraj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-14 10:13:32

Chicos usando autolayout y su sizetofit no está funcionando, a continuación, compruebe su restricción de ancho una vez. Si se ha perdido la restricción de ancho, entonces la altura será precisa.

No es necesario utilizar ninguna otra API. una sola línea solucionaría todo el problema.

[_textView sizeToFit];

Aquí, solo me preocupaba la altura, manteniendo el ancho fijo y había perdido la restricción de ancho de mi TextView en storyboard.

Y esto era para mostrar el contenido dinámico de la Servicio.

Espero que esto pueda ayudar..

 6
Author: Swaroop S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-02 06:58:22

A partir de iOS 8, es posible usar las características de diseño automático de una UITableView para cambiar automáticamente el tamaño de una UITextView sin ningún código personalizado. He puesto un proyecto en github que demuestra esto en acción, pero aquí está la clave:

  1. El UITextView debe tener el desplazamiento desactivado, lo que puede hacer mediante programación o a través del creador de interfaces. No se redimensionará si el desplazamiento está habilitado porque el desplazamiento le permite ver el contenido más grande.
  2. En viewDidLoad para el controlador UITableViewController, debe establecer un valor para estimatedRowHeight y luego establecer rowHeight a UITableViewAutomaticDimension.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.estimatedRowHeight = self.tableView.rowHeight;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}
  1. El destino de implementación del proyecto debe ser iOS 8 o superior.
 6
Author: Chuck Krutsinger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-17 06:00:42

Esto funcionó muy bien cuando necesitaba hacer que el texto en un UITextView se ajustara a un área específica:

// The text must already be added to the subview, or contentviewsize will be wrong.

- (void) reduceFontToFit: (UITextView *)tv {
    UIFont *font = tv.font;
    double pointSize = font.pointSize;

    while (tv.contentSize.height > tv.frame.size.height && pointSize > 7.0) {
        pointSize -= 1.0;
        UIFont *newFont = [UIFont fontWithName:font.fontName size:pointSize];
        tv.font = newFont;
    }
    if (pointSize != font.pointSize)
        NSLog(@"font down to %.1f from %.1f", pointSize, tv.font.pointSize);
}
 4
Author: Bill Cheswick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-01 12:48:12

Aquí está la versión swift de @jhibberd

    let cell:MsgTableViewCell! = self.tableView.dequeueReusableCellWithIdentifier("MsgTableViewCell", forIndexPath: indexPath) as? MsgTableViewCell
    cell.msgText.text = self.items[indexPath.row]
    var fixedWidth:CGFloat = cell.msgText.frame.size.width
    var size:CGSize = CGSize(width: fixedWidth,height: CGFloat.max)
    var newSize:CGSize = cell.msgText.sizeThatFits(size)
    var newFrame:CGRect = cell.msgText.frame;
    newFrame.size = CGSizeMake(CGFloat(fmaxf(Float(newSize.width), Float(fixedWidth))), newSize.height);
    cell.msgText.frame = newFrame
    cell.msgText.frame.size = newSize        
    return cell
 4
Author: Fareed Alnamrouti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-07 16:02:09

Para iOS 7.0, en lugar de configurar frame.size.height a contentSize.height (que actualmente no hace nada) use [textView sizeToFit].

Ver esta pregunta.

 3
Author: Stian Høiland,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:46

Revisé todas las respuestas y todas mantienen el ancho fijo y ajustan solo la altura. Si desea ajustar también el ancho, puede usar muy fácilmente este método:

Así que al configurar tu vista de texto, establece scroll disabled

textView.isScrollEnabled = false

Y luego en el método delegado func textViewDidChange(_ textView: UITextView) agregue este código:

func textViewDidChange(_ textView: UITextView) {
    let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
    textView.frame = CGRect(origin: textView.frame.origin, size: newSize)
}

Salidas:

introduzca la descripción de la imagen aquí

introduzca la descripción de la imagen aquí

 3
Author: Peter Stajger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-21 14:12:23

Desactivar el desplazamiento

Añadir constantes

Y añade tu texto

[yourTextView setText:@"your text"];
[yourTextView layoutIfNeeded];

Si usas UIScrollView deberías añadir esto también;

[yourScrollView layoutIfNeeded];

-(void)viewDidAppear:(BOOL)animated{
    CGRect contentRect = CGRectZero;

    for (UIView *view in self.yourScrollView.subviews) {
         contentRect = CGRectUnion(contentRect, view.frame);
    }
    self.yourScrollView.contentSize = contentRect.size;
}
 3
Author: alicanozkara,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-17 08:31:20

Espero que esto ayude:

- (void)textViewDidChange:(UITextView *)textView {
  CGSize textSize = textview.contentSize;
  if (textSize != textView.frame.size)
      textView.frame.size = textSize;
}
 1
Author: Dr. Marty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-17 17:31:32

Si cualquier otro llega aquí, esta solución funciona para mí, 1"Ronnie Liew" +4 "user63934" (Mi texto llega desde el servicio web): nota el 1000 (nada puede ser tan grande "en mi caso")

UIFont *fontNormal = [UIFont fontWithName:FONTNAME size:FONTSIZE];

NSString *dealDescription = [client objectForKey:@"description"];

//4
CGSize textSize = [dealDescription sizeWithFont:fontNormal constrainedToSize:CGSizeMake(containerUIView.frame.size.width, 1000)];

CGRect dealDescRect = CGRectMake(10, 300, containerUIView.frame.size.width, textSize.height);

UITextView *dealDesc = [[[UITextView alloc] initWithFrame:dealDescRect] autorelease];

dealDesc.text = dealDescription;
//add the subview to the container
[containerUIView addSubview:dealDesc];

//1) after adding the view
CGRect frame = dealDesc.frame;
frame.size.height = dealDesc.contentSize.height;
dealDesc.frame = frame;

Y eso es... Salud

 1
Author: Alejo JM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-30 01:56:34

La mejor manera que encontré para cambiar el tamaño de la altura de la UITextView de acuerdo con el tamaño del texto.

CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@"SAMPLE_FONT" size:14.0]
                       constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX)];

O puede USAR

CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@"SAMPLE_FONT" size:14.0]
                       constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX) lineBreakMode:NSLineBreakByTruncatingTail];
 1
Author: Manju,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-06 06:32:29

Para aquellos que quieren que textview realmente se mueva hacia arriba y mantenga la posición de la línea de fondo

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

if(frame.size.height > textView.frame.size.height){
    CGFloat diff = frame.size.height - textView.frame.size.height;
    textView.frame = CGRectMake(0, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);
}
else if(frame.size.height < textView.frame.size.height){
    CGFloat diff = textView.frame.size.height - frame.size.height;
    textView.frame = CGRectMake(0, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);
}
 1
Author: Gal Blank,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-30 21:43:46

El único código que funcionará es el que usa 'sizeToFit' como en la respuesta de jhibberd anterior, pero en realidad no lo captará a menos que lo llame en viewDidAppear o lo envíe al evento UITextView text changed.

 1
Author: Mohammad Zekrallah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-08 08:25:57

Basado en la respuesta de Nikita Took llegué a la siguiente solución en Swift que funciona en iOS 8 con diseño automático:

    descriptionTxt.scrollEnabled = false
    descriptionTxt.text = yourText

    var contentSize = descriptionTxt.sizeThatFits(CGSizeMake(descriptionTxt.frame.size.width, CGFloat.max))
    for c in descriptionTxt.constraints() {
        if c.isKindOfClass(NSLayoutConstraint) {
            var constraint = c as! NSLayoutConstraint
            if constraint.firstAttribute == NSLayoutAttribute.Height {
                constraint.constant = contentSize.height
                break
            }
        }
    }
 1
Author: Apfelsaft,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-13 12:46:46

Respuesta rápida: El siguiente código calcula la altura de su TextView.

                let maximumLabelSize = CGSize(width: Double(textView.frame.size.width-100.0), height: DBL_MAX)
                let options = NSStringDrawingOptions.TruncatesLastVisibleLine | NSStringDrawingOptions.UsesLineFragmentOrigin
                let attribute = [NSFontAttributeName: textView.font!]
                let str = NSString(string: message)
                let labelBounds = str.boundingRectWithSize(maximumLabelSize,
                    options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                    attributes: attribute,
                    context: nil)
                let myTextHeight = CGFloat(ceilf(Float(labelBounds.height)))

Ahora puede establecer la altura de su TextView en myTextHeight

 1
Author: RawMean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-18 01:55:25

Aquí está la respuesta si necesita cambiar el tamaño textView y tableViewCell dinámicamente en staticTableView

[https://stackoverflow.com/a/43137182/5360675][1]

 1
Author: Volodymyr Nazarkevych,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:27