以编程方式将UITableViewCell添加到UITableView

时间:2013-06-05 13:21:47

标签: ios uitableview

我有一个应用程序可以重新排列UITableViewCells的顺序,并可以删除单元格。但是,当按下按钮时,我需要帮助向UITableView添加新单元格,以及保存重新排列单元格顺序的方法。

以下是ViewController.m文件

中的代码
- (void)viewDidLoad
{
[super viewDidLoad];
if (!maTheData) {
    maTheData = [[NSMutableArray alloc] initWithObjects:@"Bus", @"Truck", @"Car",nil];


}
}

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath           *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tvcItems"];
UILabel *lblName = (UILabel *)[cell viewWithTag:100];
[lblName setText:[maTheData objectAtIndex:[indexPath row]]];
return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:    (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source
    [maTheData removeObjectAtIndex:[indexPath row]];
    // Delete row using the cool literal version of [NSArray arrayWithObject:indexPath]
    [tableView deleteRowsAtIndexPaths:@[indexPath]   withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Insert something into the array, and you can just add a populated NSIndexPath of   data or simplr reload data
    [maTheData addObject:@"I'm a new item!"];
    [tableView reloadData];
}
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
NSString *mover = [maTheData objectAtIndex:[fromIndexPath row]];
[maTheData removeObjectAtIndex:[fromIndexPath row]];
[maTheData insertObject:mover atIndex:[toIndexPath row]];

[tableView setEditing:NO animated:YES];

}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setEditing:YES animated:YES];
}

1 个答案:

答案 0 :(得分:2)

在您的IBAction方法(连接到您的按钮的方法)中,您只需向maTheData添加一个新条目并致电[self.tableView reloadData]

- (IBAction)addAction:(id)sender {   
  [self.maTheData addObject:@"A string object"];
  [self.tableView reloadData];
}