9

Tengo un popover de ipad que contiene un UITableView. Después de llenar la tabla, generalmente tiene solo algunos elementos (4-5), entonces estoy buscando una forma de cambiar el tamaño del popover (contentSizeForViewInPopover) a la altura real de la tabla (la altura sumada de todas sus celdas) .Altura UITableView variable en UIPopoverController (contentSizeForViewInPopover)?

Por lo tanto, tengo la altura, pero no estoy seguro de dónde llamar contentSizeForViewInPopover, traté de llamarlo en: viewDidAppear y viewWillAppear pero sin éxito ya que parece que la tabla se rellena después y la altura real solo esta disponible despues

¿Alguna idea de esto? ¡Gracias!

EDITAR: Mis celdas tienen diferentes alturas basadas en el contenido que llevan, no puedo precalcular la altura con noOfRows * cellHeight.

Respuesta

1

enfoque indirecto:

Ajuste la altura de su encargo para su UITableViewCell usando

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
return [indexPath row] * 40; 
} 

encontrar el número total de filas en un punto de su programa ... Usando el numberOfRowsInSection, obtener el número de de filas

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 

return [self.yourArray count]; 

//yourArray is the array with which you are populating the tableView 
} 

Si tiene más de una sección, multiplíquela con el resultado del número de filas para el número efectivo de filas.

Ahora

UITableView Actual Height = Height of UITableViewCell * Total number of rows. 

respuesta Actualizado:

Si los tamaños de celda varían, puede que tenga que hacer hacer uno de estos:

  1. forzar al texto a un menor tamaño para que todas las celdas tengan la misma altura ... Esto se puede hacer usando

    'sizeToFit'

  2. Deberá buscar la altura del texto utilizando otra función. Algo así como ...

    • (float) calculatedHeight { textLabel.frame.origin.ytextLabel.frame.size.height5 de retorno; }
  3. Usted puede mirar en THIS tutorial para cambiar el tamaño de UITableViewCell de texto variable.

  4. https://discussions.apple.com/thread/1525150?start=0&tstart=0

+0

Lamentablemente, mis celdas tienen diferentes alturas basadas en el contenido que llevan, no puedo precalcular la altura con 'noOfRows * cellHeight'. –

+0

compruebe la respuesta actualizada. – Legolas

0

Una forma alternativa de obtener la altura es añadir vista del UITableViewController 's con un conjunto alpha a 0.0 a la jerarquía de vistas y luego obtener el tamaño de contenido utilizando la propiedad contentSize de la vista de tabla Esto es posible ya que la vista de tabla es una subclase de la vista de desplazamiento.

Una vez que tenga el tamaño de contenido, establezca el valor de contentSizeForViewInPopover y luego empújelo en el popover.

+0

OK, eso tiene sentido, pero ¿dónde debería llamar 'contentSize'? Seguramente tiene que ser llamado después de que la tabla se haya llenado (también conocido como - tableView: cellForRowAtIndexPath: ') –

+0

Obténgalo después de haber agregado la vista de tabla invisible a la jerarquía de la vista. Debería ser 'addSubview:' seguido de 'tableView.contentSize'. –

18

Quería cambiar el contentSizeForViewInPopover cuando mi vista parecía coincidir con el UITableView y también cuando llamo al reloadData, ya que solo lo llamo cuando quito o agrego filas o secciones.

El siguiente método calcula la altura y la anchura correcta y fija el contentSizeForViewInPopover

-(void) reloadViewHeight 
{ 
    float currentTotal = 0; 

    //Need to total each section 
    for (int i = 0; i < [self.tableView numberOfSections]; i++) 
    { 
     CGRect sectionRect = [self.tableView rectForSection:i]; 
     currentTotal += sectionRect.size.height; 
    } 

    //Set the contentSizeForViewInPopover 
    self.contentSizeForViewInPopover = CGSizeMake(self.tableView.frame.size.width, currentTotal); 
} 
+4

Squeeeeeeeeeee! –

+5

Puede simplificar el cálculo haciendo 'CGRectGetMaxY ([self.tableView rectForSection: [self.tableView numberOfSections] - 1])' - solo necesita saber el borde inferior de la última sección –

+0

Gracias Ben Lings, eso de hecho es mucho más simple. – k107

11

Esta respuesta es cortesía de @BenLings de uno de los comentarios anteriores. Es una solución muy limpia y vale la pena tener su propia respuesta:

- (CGSize)contentSizeForViewInPopover { 
    // Currently no way to obtain the width dynamically before viewWillAppear. 
    CGFloat width = 200.0; 
    CGRect rect = [self.tableView rectForSection:[self.tableView numberOfSections] - 1]; 
    CGFloat height = CGRectGetMaxY(rect); 
    return (CGSize){width, height}; 
} 
+1

Esto funcionó muy bien para mí, también tuve que incorporar la altura de las tablas de encabezados o pies de página, si está presente. – tapi

+0

¿Dónde debo llamar a este método? – Isuru

1

lo hice como esta de controlador que contiene una tabla:

- (void)updatePopoverContentSize { 
    CGSize size = { CGFLOAT_MAX, CGFLOAT_MAX }; 
    size = [self.tableView sizeThatFits: size]; 
    size.width = 320; // some hard-coded value table doesn't return anything useful for width 
    size.hight = MIN(size.hight, 400); // make sure it is not too big. 

    self.contentSizeForViewInPopover = size; 
} 
1

No hay necesidad de crear un gancho artificial, esto funciona bien (en iOS 7 por lo menos):

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 

    CGSize size = self.view.bounds.size; 
    size.height = fmaxf(size.height, self.tableView.contentSize.height); 
    self.preferredContentSize = size; 
} 
0

Esto debería hacer el truco

override func viewWillLayoutSubviews() { 
     super.viewWillLayoutSubviews() 

     self.preferredContentSize = CGSizeMake(0, self.tableView.contentSize.height) 
} 
Cuestiones relacionadas