Не удалось запустить режим самостоятельного редактирования при нажатии кнопки редактирования в TableView

#ios #objective-c #iphone #uitableview

#iOS #objective-c #iPhone #uitableview

Вопрос:

Я пытаюсь создать редактируемую таблицу в приложении для iPhone. У меня есть два вопроса.

  1. Когда я нажимаю кнопку редактирования и, таким образом, вхожу в режим редактирования, я не могу удалить строку.

  2. Если есть способ добавить функцию «добавить новую ячейку» вместо того, как я сделал в своем коде? (Я добавил метод addButtonAction.)

Вот мой .h

 #import <UIKit/UIKit.h>

@interface FirstViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource>
{
    UITableView *table;
    NSMutableArray *tableDataSource;
}

-(IBAction)addButtonAction:(id)sender;

@end
  

Вот .m

 #import "FirstViewController.h"

@implementation FirstViewController

- (IBAction)addButtonAction:(id)sender
{
    if(tableDataSource != nil)
    {
        [tableDataSource addObject:@"New City"];
    }
    [table reloadData];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    tableDataSource = [[NSMutableArray alloc]init];
    [tableDataSource addObjectsFromArray:[NSArray arrayWithObjects: @"Canada", @"United States", @"Australia", @"United Kingdom", nil]];

    table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 367) style:UITableViewStyleGrouped];
    [table setDataSource:self];
    [table setDelegate:self];
    [self.view addSubview:table];

    [[self navigationItem] setLeftBarButtonItem:[self editButtonItem]];

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                              target:self
                              action:@selector(addButtonAction:)];
    [[self navigationItem] setRightBarButtonItem:addButton];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[self tableView] reloadData];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

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

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

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

    // Configure the cell...
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text = [tableDataSource objectAtIndex:indexPath.row];

    return cell;
}

#pragma - Enable/Disable Edit Button

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing
             animated:animated];

    [table setEditing:editing animated:animated];
}

#pragma - Editing Style

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
   return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) 
    {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

#pragma - Can Move Row

// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    NSString *item = [tableDataSource objectAtIndex:fromIndexPath.row];
    [tableDataSource removeObject:item];
    [tableDataSource insertObject:item atIndex:toIndexPath.row];
}

// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark - Table Title

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section == 0)
    {
        return @"City";
    }

    else 
    {
        return @"Nothing here";
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        //TBD....
    }

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
  

Ответ №1:

  1. Убедитесь, что при удалении строки из TableView также необходимо удалить объект из NSArray.
  2. Эта кнопка добавления, я думаю, будет работать, но это

    if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; }

сделайте так:

ячейка = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault повторно использовать идентификатор:идентификатор ячейки];

Просто удалите, если statament … Надеюсь, я понял ваш вопрос и эту справку.