#import <UIKit/UIKit.h>
@interface zViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITableView *table;
@end
#import "zViewController.h"
@interface zViewController ()
@property (nonatomic, retain) NSArray* data;
@end
@implementation zViewController{
BOOL _editing;
}
@synthesize data = _data;
@synthesize table = _table;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
_editing = NO;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(editButtonWasPressed:)];
[self loadRecords];
}
- (void)editButtonWasPressed:(id)sender {
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(saveButtonWasPressed:)];
[self setEditing:YES animated:YES];
}
- (void)saveButtonWasPressed:(id)sender {
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(editButtonWasPressed:)];
[self setEditing:NO animated:YES];
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
_editing = editing;
if (editing == YES) {
[self.table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:self.data.count -1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
[super setEditing:editing animated:animated];
[self.table setEditing:editing animated:animated];
if (editing == NO) {
[self.table deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:self.data.count inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
}
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
[self fetchChannels];
}
- (void)fetchChannels {
[self.table reloadData];
}
-(void) loadRecords{
self.data = @[@"Record 1", @"Record 2", @"Record 3"];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return (indexPath.row == self.data.count)? UITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _editing? self.data.count + 1 : self.data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.text = self.data[indexPath.row];
return cell;
}
@end