Delete button doesn't appear in UITableViewCell - ios

I have got an issue with getting Delete button on Edit one clicks. The problem is being that it doesn't appear at all. My code is below and it works for swiping across a cell... Thank you in advance for the help!
#import "ViewController.h"
#interface ViewController ()
#property (strong) NSArray *lessons;
#end
static NSString *identifier = #"Cell";
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.lessons = #[
#"Computer Science",
#"Math",
#"Chemistry"
];
self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.view addSubview:self.tableView];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
[self.tableView registerClass:UITableViewCell.class forCellReuseIdentifier:identifier];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.lessons.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
cell.textLabel.text = self.lessons[indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
#end
Once I pressed Edit button.
This appears when I swiped across the cell.

hear above coding see that its really useful for that.
- (HelloController *) init
{
if (!(self = [super init])) return self;
self.title = #"Table Edits";
// Initialize the table titles, so they can be edited over time
tableTitles = [[NSMutableArray alloc] init];
ithTitle = NCELLS;
for (int i = 1; i <= NCELLS; i++)
[tableTitles addObject:[NSString stringWithFormat:#"Table Cell #%d", i]];
return self;
}
#pragma mark UITableViewDataSource Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView :(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tableTitles count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"any-cell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:#"any-cell"] autorelease];
}
cell.text = [tableTitles objectAtIndex:[indexPath row]];
// cell.editingStyle = UITableViewCellEditingStyleDelete; // now read-only and no longer needed
return cell;
}
- (void) add
{
[tableTitles addObject:[NSString stringWithFormat:#"Table Cell #%d", ++ithTitle]];
[self.tableView reloadData];
}
#pragma mark UITableViewDelegateMethods
- (void) deselect
{
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}
// Respond to user selection
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath
{
printf("User selected row %d\n", [newIndexPath row] + 1);
[self performSelector:#selector(deselect) withObject:nil afterDelay:0.5f];
}
-(void)leaveEditMode
{
// Add the edit button
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithTitle:#"Edit"
style:UIBarButtonItemStylePlain
target:self
action:#selector(enterEditMode)] autorelease];
[self.tableView endUpdates];
[self.tableView setEditing:NO animated:YES];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
printf("About to delete item %d\n", [indexPath row]);
[tableTitles removeObjectAtIndex:[indexPath row]];
[tableView reloadData];
}
-(void)enterEditMode
{
// Add the edit button
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithTitle:#"Done"
style:UIBarButtonItemStylePlain
target:self
action:#selector(leaveEditMode)] autorelease];
[self.tableView setEditing:YES animated:YES];
// [self.tableView beginUpdates];
}
- (void)loadView
{
[super loadView];
// Add an add button
self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
initWithTitle:#"New"
style:UIBarButtonItemStylePlain
target:self
action:#selector(add)] autorelease];
// Add the edit button
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithTitle:#"Edit"
style:UIBarButtonItemStylePlain
target:self
action:#selector(enterEditMode)] autorelease];
}

If anyone has the same issue, then you are probably using a UITableView in a UIViewController, so it doesn't manage editions for you. When you click Edit button, you must implement TableView's editing mode AND View's editing mode manually. How have I solved that issue.
#pragma mark - Edit button listener
- (void)editButtonPressed {
if(self.editing) {
[self setEditing:NO animated:YES];
[self.tableView setEditing:NO animated:YES];
} else {
[self setEditing:YES animated:YES];
[self.tableView setEditing:YES animated:YES];
}
}
Thank you guys for commenting!

Related

showing NSMutabelArray in tableViewController in objective c

I am passing NSMutableArray to another a tableview and I want to show it in the table view. My NSMutableArray is as follows
2017-02-07 18:32:24.086 krib[13753:2978659] (
"Balcony.png",
"Utilities Included.png",
"Air-conditioning.png",
"Stove.png",
"WiFi Included.png",
"Queen Bed.png",
"Dining Table.png",
"Washing Machine.png",
"Dryer.png",
"Sofa.png",
"TV.png",
"Curtains.png",
"Refrigerator.png",
"Water Heater.png",
"Microwave Oven.png"
)
I send data as,
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"segue"]) {
MZFormSheetPresentationViewControllerSegue *presentationSegue = (id)segue;
presentationSegue.formSheetPresentationController.presentationController.shouldApplyBackgroundBlurEffect = YES;
UINavigationController *navigationController = (id)presentationSegue.formSheetPresentationController.contentViewController;
AmennitiesTableTableViewController *presentedViewController = [navigationController.viewControllers firstObject];
// presentedViewController.textFieldBecomeFirstResponder = YES;
presentedViewController.passingString = facilities;
}
and receive data in table view controller,
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Close" style:UIBarButtonItemStylePlain target:self action:#selector(close)];
NSLog(#"%#",self.passingString);
[self.tableView reloadData];
}
I tried showing the mutable array as follows,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"facilitiesCell";
AmenitiesTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
cell.facilitylbl.text = [self.passingString objectAtIndex:indexPath.row];
// Configure the cell...
return cell;
}
But I am not understanding what exactly i am missing to Populate data on the tableview.
I think you are missing to set tableview delegate & datasource.
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Close" style:UIBarButtonItemStylePlain target:self action:#selector(close)];
[self.myTable setDelegate:self];
[self.myTable setDataSource:self];
NSLog(#"%#",self.passingString);
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.passingString.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"facilitiesCell";
AmenitiesTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(self.passingString.count > 0){
cell.facilitylbl.text = [self.passingString objectAtIndex:indexPath.row];
}
// Configure the cell...
return cell;
}

UITableViewCell custom edit content

I'd like my cells to have not only the Delete button while editing but also others. So what is an actual way to do this? I've tried making own UIView object for editingAccessoryView property but the problem is being that the view appears only on direct edit (i.e. clicking Edit button in Navigation Bar) and completely ignores swipes across a cell. Also tableView:editActionsForRowAtIndexPath: method was given a try but didn't work, at least I didn't manage to figure out how to get what I want with its function. Thank you in advance!
You Try This Code
-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewRowAction *button = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:#"Button 1" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath)
{
NSLog(#"Action to perform with Button 1");
}];
button.backgroundColor = [UIColor greenColor]; //arbitrary color
UITableViewRowAction *button2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:#"Button 2" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath)
{
NSLog(#"Action to perform with Button2!");
}];
button2.backgroundColor = [UIColor blueColor]; //arbitrary color
return #[button, button2]; //array with all the buttons you want. 1,2,3, etc...
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
// you need to implement this method too or nothing will work:
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES; //tableview must be editable or nothing will work...
}
You CanTry also this code
.H File
{
NSMutableArray *dataArray;
}
#property (weak, nonatomic) IBOutlet UITableView *atableView;
#property(nonatomic,strong) NSMutableArray *dataArray;
**`.M file`**
- (void)viewDidLoad
{
[super viewDidLoad];
self.dataArray = [[NSMutableArray alloc] initWithObjects:#"Saurabh Sharma",#"Deepesh Jain",#"Ashish Sharma",#"Chandan",#"kanhaiya",#"Suchitra Bohra",#"Neha",#"Ghanshyam",nil];
self.title = #"Move Rows";
UIBarButtonItem *editButton = [[UIBarButtonItem alloc] initWithTitle:#"Edit" style: UIBarButtonItemStyleBordered target:self action:#selector(editButton:)];
[self.navigationItem setRightBarButtonItem:editButton];
// Do any additional setup after loading the view from its nib.
}
-(void)editButton:(UIBarButtonItem *)button
{
{
if(self.editing)
{
[super setEditing:NO animated:NO];
[atableView setEditing:NO animated:NO];
[atableView reloadData];
[self.navigationItem.rightBarButtonItem setTitle:#"Edit"];
[self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStylePlain];
}
else
{
[super setEditing:YES animated:YES];
[atableView setEditing:YES animated:YES];
[atableView reloadData];
[self.navigationItem.rightBarButtonItem setTitle:#"Done"];
[self.navigationItem.rightBarButtonItem setStyle:UIBarButtonItemStyleDone];
}
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dataArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifair=#"cellIdentifair";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifair];
if(cell==nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifair];
}
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#pragma delete row in table view
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionView *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 10; // This is the minimum inter item spacing, can be more
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return TRUE;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView beginUpdates];
[dataArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
[tableView endUpdates];
NSLog(#"Methods called when row is deleted");
}
#pragma Move Table View Delegte
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
NSString *item = [self.dataArray objectAtIndex:fromIndexPath.row];
[self.dataArray removeObject:item];
[self.dataArray insertObject:item atIndex:toIndexPath.row];
}
Works in Swift as well.
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
var completionButton = UITableViewRowAction(style: .Normal,
title: "Complete",
handler: {(action, index) in
/* Completion Code */
println("Complete")})
completionButton.backgroundColor = .lightGrayColor()
return [completionButton]
}
Also for iOS 11 you should use
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView leadingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath - for right swipe
and
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath - for left swipe
For ex.:
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
UIContextualAction* action = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:#"Title" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
// Do something
completionHandler(YES);
}
UISwipeActionsConfiguration * actionsConfiguration = [UISwipeActionsConfiguration configurationWithActions:#[action]];
return actionsConfiguration;
}

swipe to delete option breaking the tableviewcell functionality

So I have been creating a tableviewcontroller that handles my tableview and its tableviewcells..
Here's the code––
ItemsViewController.h
#import <UIKit/UIKit.h>
#import "DetailViewController.h"
#interface ItemsViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
-(IBAction)addNewItem:(id)sender;
#end
ItemsViewController.m
#implementation ItemsViewController
-(id) init{
self= [super initWithStyle:UITableViewStyleGrouped];
if (self) {
UINavigationItem *n= [self navigationItem];
[n setTitle:#"Homepwner"];
for (int i=0; i<5; i++) {
[[BNRItemStore sharedStore] createItem];
}
}
return self;
}
- (id)initWithStyle:(UITableViewStyle)style
{
return [self init];
}
- (void)viewDidLoad
{
NSLog(#"ItemsView loaded");
[super viewDidLoad];
UIBarButtonItem *bbi= [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(addNewItem:)];//Target-Action pair..
self.navigationItem.rightBarButtonItem= bbi;
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
}
-(void)viewWillAppear:(BOOL)animated{
NSLog(#"ItemsView appearing");
[super viewWillAppear:animated];
[[self tableView] reloadData];
}
-(IBAction)addNewItem:(id)sender{
BNRItem *newItem= [[BNRItemStore sharedStore] createItem];
NSLog(#"%d",[[[BNRItemStore sharedStore] allItems] count]);
int newRow = [[[BNRItemStore sharedStore] allItems] indexOfObject:newItem];
NSIndexPath *ip= [NSIndexPath indexPathForRow:newRow inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:ip] withRowAnimation:UITableViewRowAnimationTop];
}
//Row Selection
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if(indexPath.row<[[BNRItemStore sharedStore] allItems].count){
NSLog(#"Row# %d selected",indexPath.row);
DetailViewController *detailViewController= [[DetailViewController alloc] init];
NSArray *items= [[BNRItemStore sharedStore] allItems];
BNRItem *item= [items objectAtIndex:indexPath.row];
detailViewController.item=item;//BNRItem at the selected indexPath.
//Push it onto the top of the navigation controller's stack
[[self navigationController] pushViewController:detailViewController animated:YES];
}
else{
return;
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(#"Test1");
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
// Return the number of rows in the section.
NSLog(#"Current section- %d",section);
return [[[BNRItemStore sharedStore] allItems] count]+1 ;//no. of rows (5)+'No more items' row
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"hello");
// NSLog(#"%#",headerView);
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
if (!cell) {
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (indexPath.row<[[BNRItemStore sharedStore] allItems].count) {
[[cell textLabel] setText:[[[[BNRItemStore sharedStore] allItems] objectAt Index:indexPath.row] description]];
}
else if (indexPath.row== [[BNRItemStore sharedStore] allItems].count)
{
[[cell textLabel] setText:#"No more items"];
}
return cell;
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
if (self.editing) {
NSLog(#"Editing is on");
self.navigationItem.rightBarButtonItem.enabled=NO;
if (indexPath.row==[[BNRItemStore sharedStore] allItems].count) {
[tableView cellForRowAtIndexPath:indexPath].hidden=YES;
return NO;// Do not make 'No more items' editable.
}
}
else{//When the user is out of editing mode
NSLog(#"editing done");
[self.tableView cellForRowAtIndexPath:indexPath].hidden=NO;
self.navigationItem.rightBarButtonItem.enabled=YES;
}
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%#",NSStringFromSelector(_cmd));
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSLog(#"Deletion is on");
// Delete the row from the data source
NSArray *items= [[BNRItemStore sharedStore] allItems];
BNRItem *p= [items objectAtIndex:[indexPath row]];
[[BNRItemStore sharedStore] removeItem:p];
[tableView deleteRowsAtIndexPaths:#[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
}
}
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
[[BNRItemStore sharedStore] moveItemAtIndex:fromIndexPath.row toIndex:toIndexPath.row];
}
-(NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedIndexPath{
if (proposedIndexPath.row==[[BNRItemStore sharedStore] allItems].count) {// 'No more items' row
return [NSIndexPath indexPathForRow:proposedIndexPath.row-1 inSection:0];
}
return proposedIndexPath;
}
#end
When the editing mode is on i.e when i tap Edit button on the NavBar the Add button grays out and the 'No more items' rows becomes hidden. After exiting Edit mode (by tapping 'Done' button) the Add button becomes selectable and the 'No more items' row unhides.. This is all fine when i perform editing by first entering the Edit mode and then exiting the Edit mode. But when instead of using the above way, i use swipe to delete feature, the view doesn't realize the above functionality (i.e. Ungraying/Re-enabling the Add button once i'm done doing a deletion using the swipe to delete thing. When i swipe across a cell (so as to bring up the delete button on the right side of the cell and graying out the Add button in the process) and choose not to press the 'Delete' button by just retapping on the cell (so that the Delete button goes away) the Add button does not update itself so as to get enabled.. What to do about. Pls carefully examine my code first and give recommendations accordingly..
use this tableView Delegate mathod
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
return NO;
}
Please Utilize the Apple Library- UItableView

When I press the button, I want the content of the text field to be added- IOS TableView

i have updated my code,
everything seems good, but when i press the add button it does not add the table.
then i realized i have forgot to initialize array, then everything is ok
#import "RootViewController.h"
#import "Hello_WorldAppDelegate.h"
#implementation RootViewController
#synthesize tableView;
- (void)viewDidLoad {
// Add the following line if you want the list to be editable
// self.navigationItem.leftBarButtonItem = self.editButtonItem;
}
- (IBAction)addToTable:(id)sender{
/*
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Do you want to say hello?" message:#"More info..." delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Say Hello",nil];
[alert show];
[alert release];
*/
[myArray addObject:textField.text];
[self.tableView reloadData];
textField.text=#"";
/*
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
[cell setText:[textField text]];
[self.tableView reloadData];
*/
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return[myArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
[cell setText:[myArray objectAtIndex:indexPath.row]];
// Set up the cell
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic
}
// Override if you support editing the list
- (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:YES];
}
/*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
}*/
}
/*
Override if you support conditional editing of the list
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
Override if you support rearranging the list
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
Override if you support conditional rearranging of the list
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
}
- (void)viewDidDisappear:(BOOL)animated {
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[textField release];
[addButton release];
[super dealloc];
}
- (void)viewDidUnload {
[textField release];
textField = nil;
[addButton release];
addButton = nil;
[super viewDidUnload];
}
#end
ok i have solved my issue
thanks to everyone
Actually the problem is with your method name.
- (IBAction)addToTable:(id)sender:(UITableView *)tableView
change it like this
- (IBAction)addToTable:(id)sender
SWIFT(3.0)
#IBAction func add(_ sender: Any) {
yourarrayname.append(yourtextfield.text!)
yourtableview.reloadData()
}
what you need, first use an array as a data source for a table then on click on the button you need to add the textField content into an array then reload the table.
so your button action look like
- (IBAction)addToTable:(id)sender
{
[dataSouceArray addObject:yourTextField.text];
[yourTable reloadData];
yourTextField.text=#"";
}
and tableViewDelegate look like
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [yourDataSourceArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
[cell setText:[yourDataSourceArray objectAtIndex:indexPath.row]];
// Set up the cell
return cell;
}

Couldn't launch self.editing mode when press Edit button in TableView

I'm trying to create an editable table in iPhone App. I have two questions.
When I press the Edit button and thus enter the editing mode, I cannot delete a row.
If there's a way to add a "add new cell" function instead of the way I did in my code? (I added a addButtonAction method.)
Here's my .h
#import <UIKit/UIKit.h>
#interface FirstViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource>
{
UITableView *table;
NSMutableArray *tableDataSource;
}
-(IBAction)addButtonAction:(id)sender;
#end
Here's the .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
Make sure when you delete row from tableView also to delete the object from NSArray.
This addButton I thik will work but this
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
make like this:
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
Just remove if statament...
Hope I understand your question ant this help.

Resources