Michael Castro
Michael Castro

Reputation: 314

Show AlertController from TableViewCell, Objective-C

I've seen solutions to this problem in Swift. Can anyone help me out?

I have this method in the TableViewController class:

- (void)presentAlert {
  UIAlertController *alert = [UIAlertController
                            alertControllerWithTitle:@"Flag Content"
                            message:@"Are you sure you want to report this post?"

  UIAlertAction *okAction = [UIAlertAction
                           actionWithTitle:NSLocalizedString(@"OK", @"OK action")
                           style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction *action)
                           {
                               NSLog(@"OK action");
                               [cell.feedItem incrementKey:@"flagTotal"];
                               [cell.feedItem saveInBackground];
                               [UIView beginAnimations:nil context:nil];
                               [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:cell.flagButton cache:YES];
                               [UIView commitAnimations];
                               // Set flagButton image to checked image
                               [cell.flagButton setImage:[UIImage imageNamed:@"filledFlagButtonIcon"] forState:UIControlStateNormal];
                               [self dismissViewControllerAnimated:YES completion:nil];
                           }];

[alert addAction:okAction];
[self presentViewController:alert animated:YES completion:nil];
                            preferredStyle:UIAlertControllerStyleAlert];

I had hoped to simply call this method from the IBAction in the cell like:

- (IBAction)flagTapped:(id)sender {
  _tableView = [[FeedTableViewController alloc] init];
  [_tableView presentAlert];
}

Upvotes: 0

Views: 912

Answers (1)

Shehzad Ali
Shehzad Ali

Reputation: 1843

This is not the right approach of doing this. You can achieve this in two ways. One way is add target action in your cellForRowAtIndexPath and remove - (IBAction)flagTapped:(id)sender from your cell class and also remove its action from cell in interface builder as we are doing it programmatically like:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{


         [cell.button addTarget:self action:@selector(presentAlert) forControlEvents:UIControlEventTouchUpInside];

}

Another way of achieving this is define a protocol in your cell class. Add this method - (void)presentAlert declaration in that protocol. Set TableViewController as delegate of cell in cellForRowAtIndexPath as.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

             cell.delegate = self;
    }

Implementation of flagTapped will be like

- (IBAction)flagTapped:(id)sender {
  [self.delegate presentAlert];
}

Upvotes: 2

Related Questions