UITableViewCell: cómo manejar vistas de contenido de tamaño dinámico desde Nibs

When I want to have a custom cell, I generally add a UIView subclass to the cell's content view. For the layout of my subviews I use a nib. Then I wire up the nib to my UIView subclass. My issue is how to dynamically size content. Say my view has a lot UILabels inside it. I use layoutSubviews to position all the subviews - but it is only until that is done that I truly know the height of my cell. So currently in tableView:heightForRowAtIndexPath I setup my subview and call layoutIfNeeded so everything is positioned properly. Now I know the height of my cell and return it in the tableView:heightForRowAtIndexPath method. But now when tableView:cellForRowAtIndexPath is called the cell that I am given has a height of 44.0. When I added my subview to it - my subview is outside of its parent's bounds. Then when the cell is later resized in iOS to the height that I said I needed, my content is thrown off because of my autoresizingMask. Just trying to figure out if this is an issue others deal with or if I'm approaching it completely wrong. It just seems backwards that we ask for the height, then create a cell that is not that height.

preguntado el 03 de mayo de 12 a las 15:05

1 Respuestas

Unfortunately, this is how UITableViews work: You need to provide the heights before the UITableViewCells are actually rendered. And yes, everyone has to deal with it. :)

You could create an NSArray, add all your custom contentViews, set their frame according to the expected contentView bounds and then use this array as data source in tableView:heightForRowAtIndexPath: y tableView:cellForRowAtIndexPath:. While this isn't exactly efficient, it works fine for small data sets.

Also, here's a nice tutorial with this topic: UITableViewCell Dynamic Height (by Matt Long)

Una pregunta similar sobre SO: ¿Cómo puedo hacer correctamente las celdas de la tabla de altura variable en el iPhone?

contestado el 23 de mayo de 17 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.