2012-03-14 12 views
6

Estoy tratando de implementar la aplicación basada en UITableView. Para eso selecciono UITableViewStyle es Group.In mi TableView su es sección cada sección que tiene 1 fila.¿Por qué estamos comprobando si (celda == nil) en UITableViewController?

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 15; 
} 

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

    return 1; 
} 
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (indexPath.section==12) 
    { 
     return 120; 
    } 
    else 
    { 
     return 60; 
    } 

} 

Quiero añadir un UITextView en la Sección

Para que hice siguiente código

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



    } 
    if ([indexPath section] == 12) 
    { 
     if([indexPath row]==0) 
     { 
      descriptionTextField=[[UITextView alloc] initWithFrame:CGRectMake(5, 8, 290, 106)]; 
      descriptionTextField.font = [UIFont systemFontOfSize:15.0]; 
      descriptionTextField.backgroundColor=[UIColor scrollViewTexturedBackgroundColor]; 

      [descriptionTextField setDelegate:self]; 
      [descriptionTextField setTag:2]; 
      [descriptionTextField setText:@"Enter Location Description."]; 

      descriptionTextField.keyboardType=UIKeyboardTypeDefault; 
      descriptionTextField.returnKeyType=UIReturnKeyNext; 


      descriptionTextField.textColor=[UIColor blackColor]; 
      descriptionTextField.editable=YES; 
      descriptionTextField.autocapitalizationType=UITextAutocapitalizationTypeWords; 
      descriptionTextField.autocorrectionType=UITextAutocorrectionTypeDefault; 
      descriptionTextField.textAlignment=UITextAlignmentLeft; 

      UIToolbar* keboardToolBar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 32)]; 

      UIBarButtonItem *extra=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; 
      UIBarButtonItem *Done=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(keyboardDoneButtonActin:)]; 
      [Done setWidth:65.0f]; 
      [keboardToolBar setItems:[[[NSArray alloc]initWithObjects:extra,Done, nil]autorelease] ]; 
      [extra release]; 
      [Done release]; 

      [keboardToolBar setTintColor:[UIColor blackColor]]; 
      [keboardToolBar setAlpha:.70]; 
      [descriptionTextField setInputAccessoryView:keboardToolBar]; 
      [descriptionTextField setTag:101]; 
      [cell.contentView addSubview:descriptionTextField]; 
      [descriptionTextField release]; 
     } 
    } 

    return cell; 
} 

En el initil escenificar la vista de tabla como esta

enter image description here

si estoy desplazando la tabla hacia arriba y hacia abajo, la sección uitextView cambió y mostrará la ubicación múltiple.

enter image description here

No puedo entender por mi culpa, por qué este acaecer?

si estoy poniendo en práctica el código anterior en el lado si (célula == nil)

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

    if ([indexPath section] == 12) 
    { 
     if([indexPath row]==0) 
     { 
      **/* implemention all code here*/** 

      [cell.contentView addSubview:descriptionTextField]; 
      [descriptionTextField release]; 
     } 
    } 

    return cell; 

}

UITextView no disply, creo que no está asignando.

¿Cuál es la diferencia entre el código de la aplicación en si (célula == nil) { dentro }

si (célula == nil) {} fuera del lado

+0

La diferencia es que cuando escribes el código dentro de la celda == nil, solo funcionará una vez al comenzar si escribes un lado creará cada vez que la vista carga –

+0

por qué el valor de la sección cambió si se desplazó la vista de tabla. si yo escribo el código por el lado? –

+0

una cosa más que puede hacer en su código establezca un valor de etiqueta para la vista de texto y luego escriba este código [[cell.contentView viewWithTag: 100 + indexPath.row] removeFromSuperview]; 100 + index.row es el valor de etiqueta –

Respuesta

-2
NSString *CellIdentifier = [NSString stringWithFormat:@"%i",indexPath.row]; 

// Dequeue or create a cell of the appropriate type. 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

Esto puede ser usado en lugar de

static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

este es el ejemplo simple para escribir dentro de la célula == nill

- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"CellIdentifier"; 
// Dequeue or create a cell of the appropriate type. 
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier]; 
cell= nil; 
if (cell == nil) 
{ 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    [[cell.contentView viewWithTag:100+indexPath.row] removeFromSuperview]; 

    UIView *selectview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, cell.frame.size.width, 30)]; 
    [selectview setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"strip_s12A-1_h.png"]]]; 
    cell.selectedBackgroundView = selectview; 
    [selectview release]; 

    UILabel *cellTitle=[[UILabel alloc]initWithFrame:CGRectMake(40, 0, 300, 30)]; 
    //cellTitle.adjustsFontSizeToFitWidth=YES; 
    [cellTitle setBackgroundColor:[UIColor clearColor]]; 
    [cellTitle setFont:[UIFont fontWithName:@"Arial Rounded MT Bold" size:17]]; 
    [cellTitle setTextColor:[UIColor blackColor]]; 
    cellTitle.tag = 100+indexPath.row; 

     cellTitle.text= [[[cellArray objectAtIndex:indexPath.section]objectAtIndex:indexPath.row] valueForKey:@"Des2"]; 

    [cell.contentView addSubview:cellTitle]; 

    [cellTitle release]; 
} 
return cell; 
    } 

creo que será suficiente derecho sólo

+0

¿Es posible crear UITextView dentro if (cell == nil) –

+1

? Verifique el código anterior ahora también funciona bien –

+0

¿Esto funciona para usted o más necesario .....? –

3

El La prueba if (cell == nil) maneja el caso donde no hay celdas reutilizables para dequear, en cuyo caso debe crear una nueva celda. Cuando crea la nueva celda, usted es responsable de construir su jerarquía de vistas.

+0

si no le importa puede elaborar un poco más .. –

+2

@MusthafaPP Las células se reciclan, en lugar de crear instancias nuevas. La razón: rendimiento, velocidad. Más a menudo en [OOP] (https://en.wikipedia.org/wiki/Object-oriented_programming), creamos nuevas instancias (objetos) según sea necesario. Pero la creación de instancias de un objeto nuevo tiene algunos gastos generales, toma un poco de tiempo. En casos excepcionales, como UITableView, necesitamos el máximo rendimiento. Reciclar un objeto existente, al restablecer sus propiedades/variables clave apropiadas para uso reciente, ahorra suficiente tiempo como para justificar la molestia. Entonces, si tiene una celda disponible, vuelva a usarla. De lo contrario, crea una nueva instancia. –

Cuestiones relacionadas