Question

I have my first viewController "SFCrearMomentoViewController" and the second view is a tableViewController "MasterViewController". I need to select a row didSelectRowAtIndexPath and call the method didCelected which is implemented in my "first viewController" and close the view using dismissViewControllerAnimated.

The problem is that the method didCelected is never called. I've already tested this code in a test project using "two viewControllers" and it works but I don't know what's the problem in my current project.

SFCrearMomentoViewController.h

...
#import "MasterViewController.h"
@interface SFCrearMomentoViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate, MasterViewControllerDelegate>{
    UIImagePickerController *picker;
}
...

SFCrearMomentoViewController.m

...
-(void)didSelected:(NSString *)nombre{
    NSLog(@"didSelected method %@", nombre);
}


@end

MasterViewController.h

#import <UIKit/UIKit.h>

@protocol MasterViewControllerDelegate <NSObject>

@required
-(void) didSelected:(NSString *)nombre;

@end

@interface MasterViewController : UITableViewController

@property (weak, nonatomic) id <MasterViewControllerDelegate> delegate;

@end

MasterViewController.m

...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [self.delegate didSelected:@"row selected"];
    [self dismissViewControllerAnimated:YES completion:nil];
}
...

Solution: I had to set the delegate self. I implemented it in the Segue.

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:[MasterViewController class]]) {
        MasterViewController *nextView = segue.destinationViewController;
        nextView.delegate = self;
    }
}
Was it helpful?

Solution 2

You need to set the delegate in SFCrearMomentoViewController, you can do it in viewDidLoad, for example.

masterViewController.delegate = self;

I assume that you allocated and initialised new masterViewController object of MasterViewController type.

OTHER TIPS

I had the same problem a few hours ago. In my case I set the delegate in prepareForSegue to the segue.destinationViewController but my destination view controller wasn't the View Controller with the delegate, it was a UINavigationController. So I used this one:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"modalNeuerRaum"])
    {
        [(MyCustomModalViewController*)[(UINavigationController*)segue.destinationViewController viewControllers][0] setDelegate:self];
    }
}

That worked for me, but I don't know if you have a UINavigationController..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top