Custom delete button in uitableview cell don't work - iphone

I made tableView with filteredReservations array wich contains Rezervacija objects.
I added custom button "board", and when button is clicked, I ask with alert view to confirm this and then sending request to server. When receive server's response I need to delete row from table and object from filteredReservations array.
When I delete first row it's ok, but after that in filteredReservations instead of Rezervacija object, I got UIButton objects! I don't know HOW :)
Code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return([filteredReservations count]);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
}
Reservation *reservation = [filteredReservations objectAtIndex:indexPath.row];
NSString *label = [[NSString alloc] initWithFormat:#"%# (%d)", reservation.name, reservation.seatsNumber];
cell.textLabel.text = label;
[label release];
[reservation release];
tableView.allowsSelection = FALSE;
UIButton *cellButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[cellButton setFrame:CGRectMake(430.0, 2.0, 106.0, 40.0)];
[cellButton setTitle:#"Board" forState:UIControlStateNormal];
[cellButton addTarget:self action:#selector(BoardPassengers:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:cellButton];
cellButton.tag = indexPath.row;
return cell;
}
-(void)BoardPassengers:(id)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Question" message:#"Do you want to board passengers?"
delegate:self cancelButtonTitle:#"Odustani" otherButtonTitles:#"Da", nil];
[alert show];
[alert release];
passengerForBoarding = [NSIndexPath indexPathForRow:((UIControl*)sender).tag inSection:1];
}
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
// the user clicked one of the OK/Cancel buttons
if (buttonIndex == 0)
{
NSLog(#"cancel");
}
else
{
Reservation *reservationNew = [filteredReservations objectAtIndex:passengerForBoarding.row];
NSString *reservationId = [[NSString alloc] initWithFormat:#"%d",reservationNew.reservationId];
params = [NSDictionary dictionaryWithObjectsAndKeys: #"1", #"tour_id", #"1", #"bus_number",reservationId, #"reservation_id", nil];
[[RKClient sharedClient] post:#"/service/boardingToBus.json" params:params delegate:self];
[DSBezelActivityView newActivityViewForView:self.view withLabel:#"Boarding..."];
}
}
- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response {
if([[request resourcePath] isEqualToString:#"/service/boardingToBus.json"]){
if([[response bodyAsString] isEqualToString:#"ERROR"]){
[DSBezelActivityView removeViewAnimated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:#"Error."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}else{
[DSBezelActivityView removeViewAnimated:YES];
[filteredReservations removeObjectAtIndex:passengerForBoarding.row];
[self.tableView reloadData];
//[self.tableView beginUpdates];
//[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:passengerForBoarding]
// withRowAnimation:UITableViewRowAnimationFade];
// NSLog(#"%i", passengerForBoarding.row);
//[self.tableView endUpdates];
}
}
}

It sounds like you need to make sure the table view is explicitly aware of how many filtered reservations it needs to display.
// assuming only one section for your table view
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return([filteredReservations count]);
}
For more info:
http://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/Reference/Reference.html#//apple_ref/occ/intfm/UITableViewDataSource/tableView:numberOfRowsInSection:

Hey you can get the value of "Reservation ID" By this.
-(void)BoardPassengers:(id)sender{
Reservation *reservationNew = [filteredReservations objectAtIndex:[sender tag]];
NSString *reservationId = [NSString StringWithFormat:#"%d",reservationNew.reservationId];}
Or you can use this value anywhere you want like you have mentioned via alert-box.

Related

Accessorybutton not hiding in empty tabelview

In my application i have used the setAccessoryType,While searching the content it shows the some set of datas in tabel view with accesory button,When i clear the search it the tabelview get reloaded .Datas cleared but accessory arrow stays there itself .Here my code,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"CellIdentifier";
UILabel *l1;
UITableViewCell *cell = (UITableViewCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
l1=[[UILabel alloc]initWithFrame:CGRectMake(0, 5, 690, 40)];
}else{
l1=[[UILabel alloc]initWithFrame:CGRectMake(0, 5, 310, 40)];
}
l1.textColor=[UIColor whiteColor];
l1.backgroundColor=[UIColor clearColor];
[l1 setFont:[UIFont boldSystemFontOfSize:14.0]];
l1.textAlignment=UITextAlignmentLeft;
l1.text=[[existingResults objectAtIndex:0] valueForKey:#"food_name"];
l1.textColor=[UIColor blackColor];
[cell addSubview:l1];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
tabelview reloading code
-(void)txttapped:(id)sender{
[[WebService sharedInstance]foodsearch:txtSearch.text withCompletionHandler:^(BOOL result)
{
if(result)
{
NSLog(#"Success");
NSManagedObjectContext *context = [[DataAccessLayer sharedInstance] managedObjectContext];
existingResults = [context fetchObjectsForEntityName:NSStringFromClass([Food class]) withSortColumn:nil withSortDescending:FALSE withPredicate:nil];
[existingResults retain];
[tableView reloadData];
[self.progress hide:YES];
}
else
{
if (txtSearch.text.length==0)
{
[tableView reloadData];// tabelview reloads here
}
else
{
NSLog(#"Failure");
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:#"Alert Message" message:#" Failed" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
[alertView release];
[self.progress hide:YES];
}
}
}];
}
How to hide the accessory view when tabel has no value?Please help me to sort it out
Try ,
if([[[existingResults objectAtIndex:0] valueForKey:#"food_name"] length] > 0)
{
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}

How do I replace the date with a writable title?

When I add a new row, it currently adds a new row with the current date as the title. Below is the code that I have. What do I change "NSDate date" to so that the user can input whatever title they want?
(void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
You could use the new UIAlertView with plain text entry. You'll also have to change your table view cell to display an NSString instead of an NSDate. (Oh, and you have to adopt the UIAlertViewDelegate in the class.
-(void)insertNewObject:(id)sender
{
UIAlertView * getTitle = [[UIAlertView alloc] initWithTitle:#"title" message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil]; // should give proper cancel/accept buttons
getName.alertViewStyle = UIAlertViewStylePlainTextInput;
[getTitle show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
NSString * userEnteredThisString = [[alertView textFieldAtIndex:0] text];
[_objects insertObject:userEnteredThisString atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

Deleting core data single entry through table iPhone

Using core data to populate my table view. The thing I am not getting is that how can I delete a single entry from the core data.
Here is the code I am using:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == favouritesTable) {
cellValue = [licensePlateArray objectAtIndex:indexPath.row];
} else { // handle search results table view
cellValue = [filteredListItems objectAtIndex:indexPath.row];
}
static NSString *CellIdentifier = #"vlCell";
VehicleListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSLog(#"Cell Created");
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:#"VehicleListCell" owner:nil options:nil];
for (id currentObject in nibObjects) {
if ([currentObject isKindOfClass:[VehicleListCell class]]) {
cell = (VehicleListCell *)currentObject;
}
}
UILongPressGestureRecognizer *pressRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(tableCellPressed:)];
pressRecongnizer.minimumPressDuration = 0.5f;
[cell addGestureRecognizer:pressRecongnizer];
[pressRecongnizer release];
}
cell.textLabel.font = [UIFont systemFontOfSize:10];
Favouritesdata *favdata = [licensePlateArray objectAtIndex:indexPath.row];
[[cell ignition] setImage:[UIImage imageNamed:#"ignition.png"]];
[[cell direction] setImage:[UIImage imageNamed:#"south.png"]];
cell.licPlate.text = [favdata licenseplate];
NSLog(#"cellvalue for cellforRow: %#", cell.licPlate.text);
return cell;}
In the method of UILongPressGestureRecognizer:
- (void)tableCellPressed:(UILongPressGestureRecognizer *)recognizer{
if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles: nil] ;
[alert addButtonWithTitle:#"Remove from Favourites"];
[alert addButtonWithTitle:#"Take to Map"];
[alert show];}
In alert view method:
-(void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString *title = [alert buttonTitleAtIndex:buttonIndex];
NSManagedObjectContext *contextFav = [app managedObjectContext];
Favouritesdata * favourites = [NSEntityDescription insertNewObjectForEntityForName:#"Favouritesdata" inManagedObjectContext:contextFav];
if([title isEqualToString:#"Remove from Favourites"])
{
NSLog(#"cellValueForLongPress: %#", cellValueForLongPress);
if (cellValueForLongPress <= 0) {
NSLog(#"No data to delete");
}
else {
favourites.licenseplate = cellValueForLongPress;
}
[alert dismissWithClickedButtonIndex:0 animated:YES];
}
else if([title isEqualToString:#"Take to Map"])
{
NSLog(#"Go to MapView");
}
NSError *error;
if (![context save:&error]) {
NSLog(#"Error Occured");
}}
If you want to delete managed object from CoreData storage then you should have:
Reference to NSManagedObjectContext from where you will remove object : context
Reference to NSManagedObject that you want to delete: object
Then it will be very simple to remove object:
[context deleteObject:object];
You should know
index of the row to remove, for example, i.
retrieve it from your array: NSObject *object = [licensePlateArray objectAtIndex:i];
remove it from db : [context deleteObject:object];
remove it from array: [licensePlateArray removeObject:object];
You have to identify your NSManagedObject and then call deleteObject on your managedObjectContext. Then this object will be removed from your core data.
But you have to provide a mechanism to "somehow" get the object behind a specific tableview row.

Issue removing core data entry by selecting a row on table view

Using core data to populate my table view. The thing I am not getting is that how can I delete a single entry from the core data.
I am using uitableview not the controller.
Here is the code I am using:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == favouritesTable) {
cellValue = [licensePlateArray objectAtIndex:indexPath.row];
} else { // handle search results table view
cellValue = [filteredListItems objectAtIndex:indexPath.row];
}
static NSString *CellIdentifier = #"vlCell";
VehicleListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSLog(#"Cell Created");
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:#"VehicleListCell" owner:nil options:nil];
for (id currentObject in nibObjects) {
if ([currentObject isKindOfClass:[VehicleListCell class]]) {
cell = (VehicleListCell *)currentObject;
}
}
UILongPressGestureRecognizer *pressRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(tableCellPressed:)];
pressRecongnizer.view.tag = indexPath.row;
pressRecongnizer.minimumPressDuration = 0.5f;
[cell addGestureRecognizer:pressRecongnizer];
[pressRecongnizer release];
}
cell.textLabel.font = [UIFont systemFontOfSize:10];
Favouritesdata *favdata = [licensePlateArray objectAtIndex:indexPath.row];
[[cell ignition] setImage:[UIImage imageNamed:#"ignition.png"]];
[[cell direction] setImage:[UIImage imageNamed:#"south.png"]];
cell.licPlate.text = [favdata licenseplate];
NSLog(#"cellvalue for cellforRow: %#", cell.licPlate.text);
return cell;}
In the method of UILongPressGestureRecognizer:
- (void)tableCellPressed:(UILongPressGestureRecognizer *)recognizer{
if (recognizer.state != UIGestureRecognizerStateBegan) {
return;
}
VehicleListCell* cell = (VehicleListCell *)[recognizer view];
cellValueForLongPress = cell.licPlate.text;
NSLog(#"cell value: %#", cellValueForLongPress);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles: nil] ;
alert.tag = recognizer.view.tag;
[alert addButtonWithTitle:#"Remove from Favourites"];
[alert addButtonWithTitle:#"Take to Map"];
[alert show];}
here in alert view method the selected row will be deleted (if([title isEqualToString:#"Remove from Favourites"])):
-(void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString *title = [alert buttonTitleAtIndex:buttonIndex];
NSManagedObjectContext *contextFav = [app managedObjectContext];
Favouritesdata * favourites = [NSEntityDescription insertNewObjectForEntityForName:#"Favouritesdata" inManagedObjectContext:contextFav];
if([title isEqualToString:#"Remove from Favourites"])
{
NSLog(#"cellValueForLongPress: %#", cellValueForLongPress);
///////// to remove the object from core data
[licensePlateArray removeObjectAtIndex:alert.tag];
}
else if([title isEqualToString:#"Take to Map"])
{
NSLog(#"Go to MapView");
}
NSError *error;
if (![context save:&error]) {
NSLog(#"Error Occured");
}
[favouritesTable reloadData];}
Write this in cellForRowAtIndexPath
UILongPressGestureRecognizer *pressRecongnizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(tableCellPressed:)];
pressRecongnizer.view.tag = indexPath.row;
pressRecongnizer.minimumPressDuration = 0.5f;
[cell addGestureRecognizer:pressRecongnizer];
[pressRecongnizer release];
and use alertview like this
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:nil delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles: nil] ;
alert.tag = recognizer.view.tag;
[alert addButtonWithTitle:#"Remove from Favourites"];
[alert addButtonWithTitle:#"Take to Map"];
[alert show];
then write this in -(void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
[YourArray removeObjectAtIndex:alert.tag];
[YourTable reloadData];
Please use this code at appropriate place in your code..
Happy Coding..

UITable view button.tag to get value of row

I am having Tableview which shows comments on facebook post. I am getting comments in Array and comments Id in second array ..I have taken one uibutton in tableview cell. on that button I want to get comment id of particular comment so that I can pass that id to like method..But It is always taking id Of last comment..How can I ID of comment on Button.tag property,, My code is :
- (NSInteger)tableView:(UITableView *)atableView numberOfRowsInSection:(NSInteger)section {
return [[facebook comments] count];
}
- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
like = [UIButton buttonWithType:UIButtonTypeRoundedRect];
like.frame = CGRectMake(60, 70, 40, 20);
[like setTitle:#"like" forState:UIControlStateNormal];
[like setTag:indexPath.row];
[like addTarget:self action:#selector(likeComment) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:like];
;
cell.textLabel.font = [UIFont fontWithName:#"Arial" size:10.0];
cell.detailTextLabel.font = [UIFont fontWithName:#"Arial" size:12.0];
cell.textLabel.text = [[facebook commentId]objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [[facebook comments]objectAtIndex:indexPath.row];
NSLog(#"%# person like this",[facebook likesCount] );
NSLog(#"%# person like this comment",[facebook commentLikes]);
return cell;
}
- (void )likeComment {
NSString *idStr = [NSString stringWithFormat:#"%#/likes",[[facebook commentId]objectAtIndex:like.tag]];
[fbGraph doGraphPost:idStr withPostVars:nil];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"You like this"
message:#"" delegate:nil
cancelButtonTitle:#"Ok" otherButtonTitles:nil ];
[alert show];
[alert release];
}
Please help
The problem, which you are facing because you are always using the last like button.
You require to make few changes, Append an in the function name like likeComment:.
[like addTarget:self action:#selector(likeComment:) forControlEvents:UIControlEventTouchUpInside];
And modify your likeComment method like below.
- (void )likeComment:(id) sender {
UIButton* myLikeButton = (UIButton*)sender;
NSString *idStr = [NSString stringWithFormat:#"%#/likes",[[facebook commentId]objectAtIndex:myLikeButton.tag]];
[fbGraph doGraphPost:idStr withPostVars:nil];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"You like this"
message:#"" delegate:nil
cancelButtonTitle:#"Ok" otherButtonTitles:nil ];
[alert show];
[alert release];
}