用户在表视图控制器中向行单元添加行/节

时间:2014-03-20 17:49:47

标签: ios ios7 xcode5 uitableview

我想创建一个类似于" New Contact"的屏幕。 iPhone联系人应用程序的屏幕。有一点绿色' +' "添加电话","添加电子邮件"等等。当用户点击这些新行时(或者在"添加地址"的情况下)我想新的部分已经创建了。

如何在Table View Controller中创建类似的行为?

谢谢,丹尼尔

2 个答案:

答案 0 :(得分:1)

这是一个如何向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;
}

Tableview中应该有一个新行。下一步是替换" Some Text"用我们自己的数据。

答案 1 :(得分:0)

这是我将采取的一般方法。

创建一个自定义的tableview单元格,并使用类似

的内容为其创建委托
-(void)actionButtonTappedInTableViewCell:(UITableViewCell*)cell;

使您的视图控制器成为tableview单元格的委托,并在触发该操作时执行以下操作:

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

添加"特殊"的索引路径行到数组和cellForRow方法检查这是否是一个特殊行并将其设置为这样。

相关问题