2011-03-25 17 views
7

Soy nuevo en Objective-c. Tengo un tableView con 3 filas y 1 sección. ¿Puede ayudarme a agregar filas con texto en una tabla presionando el botón (addCity)?¿Cómo puedo insertar una fila en una tabla?

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    m_bg.image = [UIImage imageNamed:[WeatherAppDelegate isNight] ? @"SettingsBackNight.png" : @"SettingsBackDay.png" ]; 
    tableView.layer.cornerRadius = 10; 
    m_scrollView.layer.cornerRadius = 10; 
    [m_scrollView setContentSize:CGSizeMake(tableView.frame.size.width, tableView.frame.size.height)]; 
    dataArray = [[NSMutableArray alloc] initWithObjects:@"Moscow", @"London", @"Paris", nil]; 

} 


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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [dataArray count]; 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *MyIdentifier = @"MyIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 

    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease]; 
    } 

    [cell.textLabel setText: [dataArray objectAtIndex:indexPath.row]]; 
    return cell; 
} 


-(IBAction)addCity:(id)sender 
{ 
    [dataArray addObject:@"City"]; 
    NSArray *paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:[dataArray count]-1 inSection:1]]; 
    [[self tableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationTop]; 
    [tableView reloadData]; 
} 
+0

He actualizado mi código. No funciona – Sveta

+0

¡He eliminado insertRowsAtIndexPaths y mi programa está funcionando! – Sveta

Respuesta

13

Su tabla debe tomar sus datos de alguna fuente donde puede agregar elementos cuando sea necesario. (digamos, instancia de NSMutableArray en su fuente de datos), entonces se verán sus métodos. Por simplicidad se supone que tiene DataArray NSStrings que contienen:

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [dataArray count]; 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *MyIdentifier = @"MyIdentifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 
    if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease]; 
    } 
    [cell.textLabel setText: [dataArray objectAtIndex:indexPath.row]; 
    return cell; 
} 


-(IBAction)addCity:(id)sender 
{ 
    [tableView beginUpdates]; 
    [dataArray addObject:@"City"]; 
    NSArray *paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:[dataArray count]-1 inSection:1]]; 
    [[self tableView] insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationTop]; 
    [tableView endUpdates]; 
} 
+0

Algo así? dataArray = [[NSMutableArray alloc] initWithObjects: @ "Moscow", @ "London", @ "Paris", nil]; Mi programa se cuelga – Sveta

+0

@Sveta, sí la matriz debería crearse de esta manera ... ¿todavía tiene un bloqueo? – Vladimir

+0

No, he eliminado insertRowsAtIndexPaths y mi programa está funcionando. – Sveta

2

no inserta filas en la tableView directamente. Usted adoptó el protocolo UITableViewDataSource. Su origen de datos proporciona al objeto de vista de tabla la información que necesita para construir y modificar una vista de tabla. UITableViewDataSource Protocol Reference

Además, mirando su código de muestra, ha codificado el número de filas en su tabla a 3. Por lo tanto, UITableView solo mostrará 3 filas. Necesita algo como esto:

// You have a city array you created 
NSMutableArray *cityArray = ...... 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [cityArray count]; 
} 

-(IBAction)addCity:(id)sender 
{ 
    // create a new city object 
    // add the object to your array 
    [cityArray addObject:.... 
    // refresh the table 
    [tableView reloadData]; 
} 
+0

Creo que quiere insertar filas individuales y tener una buena animación, su método no proporciona una buena animación. –

Cuestiones relacionadas