2010-06-10 9 views
28

Tengo una vista para el iPhone que básicamente se divide en dos, con una pantalla informativa en la mitad superior, y una UITableView para seleccionar acciones en la mitad inferior. El problema es que no hay borde o separador sobre la primera celda en UITableView, por lo que el primer elemento de la lista se ve raro. ¿Cómo puedo agregar un separador adicional en la parte superior de la tabla, para separarlo del área de visualización que se encuentra sobre él?¿Cómo agrego un separador adicional a la parte superior de una UITableView?

Aquí está el código para construir las celdas, es bastante sencillo. El diseño general se maneja en un xib.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    } 

    switch(indexPath.row) { 
     case 0: { 
      cell.textLabel.text = @"Action 1"; 
      break; 
     } 
     case 1: { 
      cell.textLabel.text = @"Action 2"; 
      break; 
     } 
     // etc....... 
    } 
    return cell; 
} 

Respuesta

11

Tuve el mismo problema y no pude encontrar una respuesta. Así que agregué una línea al final de mi encabezado de tabla.

CGRect tableFrame = [[self view] bounds] ; 
CGFloat headerHeight = 100;   
UIView * headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableFrame.size.width, headerHeight)]; 
// Add stuff to my table header... 

// Create separator 
UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, headerHeight-1, tableFrame.size.width, 1)] ; 
lineView.backgroundColor = [UIColor colorWithRed:224/255.0 green:224/255.0 blue:224/255.0 alpha:1.0]; 
[headerView addSubview:lineView]; 

self.tableView.tableHeaderView = headerView; 
14

Acabo de golpear con este mismo problema y me di cuenta de que el separador en la parte superior solo se muestra mientras se desplaza por la mesa.

Lo que se hizo fue la siguiente

  1. En Interface Builder ir a "Scroll Ver Tamaño"
  2. Establecer los recuadros contenido de arriba a 1

alternativa en el código que podría hacer

[tableView setContentInset:UIEdgeInsetsMake(1.0, 0.0, 0.0, 0.0)]; 

NOTA: Esto ya no funciona para iOS7 ya que los separadores ya no son mostrado en absoluto.

+0

+1 esto lo arregló para mí – MCKapur

+0

+1 mucho más fácil. –

0

Resolví esto agregando una línea adicional al principio de la tabla. Solo tiene que establecer su altura en 1, configurar el texto en vacío, deshabilitar la interacción del usuario para ello y en todo el código ajustar el valor indexPath.row.

0

Añadir un separador entre la vista de encabezado y la primera fila: - En vista de cabecera en el método delegado de la sección añadir un self.separator subvista // @ propiedad (no atómica, fuerte) UIImageView * separador;

- (CGFloat)tableView:(UITableView *)tableView 
heightForHeaderInSection:(NSInteger)section { 

return 41; 
} 


- (UIView *)tableView:(UITableView *)tableView 
viewForHeaderInSection:(NSInteger)section { 

self.headerView = [[UIView alloc] init]; 
self.headerView.backgroundColor = [UIUtils colorForRGBColor:TIMESHEET_HEADERVIEW_COLOR]; 

self.separator = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"seperator.png"]]; 
self.separator.frame = CGRectMake(0,40,self.view.frame.size.width,1); 
[self.headerView addSubview:self.separator]; 
return self.headerView; 

} 
44

Para replicar las líneas de separación estándar de iOS, uso un 1 px (no 1 pt) línea del cabello tableHeaderView con la vista de tabla separatorColor:

// in -viewDidLoad 
self.tableView.tableHeaderView = ({UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 1/UIScreen.mainScreen.scale)]; 
    line.backgroundColor = self.tableView.separatorColor; 
    line; 
}); 

Lo mismo en Swift (gracias, Dane Jordan , Yuichi Kato, de Tony Merritt):

let px = 1/UIScreen.main.scale 
let frame = CGRect(x: 0, y: 0, width: self.tableView.frame.size.width, height: px) 
let line = UIView(frame: frame) 
self.tableView.tableHeaderView = line 
line.backgroundColor = self.tableView.separatorColor 
+3

como se llama usando el ({objeto}); ¿notación? – Oritm

+4

Esto se llama expresión de declaración (http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html). Por supuesto, también podría escribirlo sin él, pero se ajusta a la definición de UIView. –

+0

Sí, especialmente cuando hay muchas cosas que suceden en viewdidload. ¡Gracias por esto! – Oritm

2

En complemento de Ortwin's answer, si es necesario añadir un poco de margen a su separador superior para adaptarse a la inserción del separador, tiene t o incrustado su separador superior en otra vista:

UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 1/UIScreen.mainScreen.scale)]; 
UIView *topSeparator = [[UIView alloc] initWithFrame:CGRectMake(self.tableView.separatorInset.left, 0, self.tableView.frame.size.width - self.tableView.separatorInset.left - self.tableView.separatorInset.right, 1/UIScreen.mainScreen.scale)]; 
topSeparator.backgroundColor = self.tableView.separatorColor; 
[headerView addSubview:topSeparator]; 
self.tableView.tableHeaderView = headerView; 

Espero que ayude.

2

Hice una extensión UITableView que muestra un separador de estilo nativo en la parte superior de UITableView, mientras que la tabla se desplaza.

Here is how it looks

Aquí está el código (Swift 3)

fileprivate var _topSeparatorTag = 5432 // choose unused tag 

extension UITableView { 

    fileprivate var _topSeparator: UIView? { 
     return superview?.subviews.filter { $0.tag == _topSeparatorTag }.first 
    } 

    override open var contentOffset: CGPoint { 
     didSet { 
      guard let topSeparator = _topSeparator else { return } 

      let shouldDisplaySeparator = contentOffset.y > 0 

      if shouldDisplaySeparator && topSeparator.alpha == 0 { 
       UIView.animate(withDuration: 0.15, animations: { 
        topSeparator.alpha = 1 
       }) 
      } else if !shouldDisplaySeparator && topSeparator.alpha == 1 { 
       UIView.animate(withDuration: 0.25, animations: { 
        topSeparator.alpha = 0 
       }) 
      } 
     } 
    } 

    // Adds a separator to the superview at the top of the table 
    // This needs the separator insets to be set on the tableView, not the cell itself 
    func showTopSeparatorWhenScrolled(_ enabled: Bool) { 
     if enabled { 
      if _topSeparator == nil { 
       let topSeparator = UIView() 
       topSeparator.backgroundColor = separatorColor?.withAlpha(newAlpha: 0.85) // because while scrolling, the other separators seem lighter 
       topSeparator.translatesAutoresizingMaskIntoConstraints = false 

       superview?.addSubview(topSeparator) 

       topSeparator.leftAnchor.constraint(equalTo: self.leftAnchor, constant: separatorInset.left).isActive = true 
       topSeparator.rightAnchor.constraint(equalTo: self.rightAnchor, constant: separatorInset.right).isActive = true 
       topSeparator.topAnchor.constraint(equalTo: self.topAnchor).isActive = true 

dejar que onePixelInPoints = CGFloat (1)/UIScreen.main.scale topSeparator.heightAnchor.constraint (equalToConstant: onePixelInPoints) .isActive = verdadera

   topSeparator.tag = _topSeparatorTag 
       topSeparator.alpha = 0 

       superview?.setNeedsLayout() 
      } 
     } else { 
      _topSeparator?.removeFromSuperview() 
     } 
    } 

    func removeSeparatorsOfEmptyCells() { 
     tableFooterView = UIView(frame: .zero) 
    } 
} 

Para activarlo, simplemente llame tableView.showTopSeparatorWhenScrolled(true) después de establecer su delegate para su UITableView

+0

¿Qué es LayoutHelper? – Voyteck

+0

Lo siento, esta es mi propia clase. Reemplacé esta llamada a método con una solución genérica. – fl034

Cuestiones relacionadas