简体   繁体   中英

User adding rows/sections to static cells in Table View Controller

I'd like to create a screen similar to the "New Contact" screen of the iPhone Contacts app. There are little green '+' signs next to "add phone", "add email", etc. When the user clicks on these, new rows (or in the case of "add address", I suppose new sections) are created.

How can I create a similar behaviour in my Table View Controller?

Thanks, Daniel

here is an example how to add lines to a TableView:

// holding your data
NSMutableArray* data;

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [data count];
}

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    //if you want to add a section with one row:
    NSMutableArray *row = [[NSMutableArray alloc] init];
    [row addObject:@"Some Text"];
    [data addObject:row];
    [tableView reloadData];

    //if you want to add a row in the selected section:
    row = [data objectAtIndex:indexPath.section];
    [row addObject:@"Some Text"];
    [tableView reloadData];
}

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

    cell.textLabel.text = [[data objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];

    return cell;
}

There should be a new row in your Tableview. Next step is to replace "Some Text" with our own data.

This is the general approach I would take.

Create a custom tableview cell and create a delegate for it with something like

-(void)actionButtonTappedInTableViewCell:(UITableViewCell*)cell;

Make your view controller the delegate for the tableview cell and when that action gets triggered do the following:

-(void)actionButtonTappedInTableViewCell:(UITableViewCell*)cell
{
    NSIndexPath *oldIndexPath = [self.tableView indexPathForCell:cell];
    NSIndexPath *pathToInsert = [NSIndexPath indexPathForRow:(oldIndexPath.row + 1) inSection:oldIndexPath.section];

    [self.tableView beginUpdates];

    //now insert with whatever animation you'd like
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:pathToInsert] withRowAnimation:UITableViewRowAnimationAutomatic];


    [self.tableView endUpdates];
}

Add the index paths of your "special" rows to arrays and in your cellForRow method check if this is a special row and set it up as such.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM