问题
I've set up a delegate methos to communicate from my masterViewController
to my detailViewController
but the delegate method isn't getting called.
MasterViewController.h
#import <UIKit/UIKit.h>
@class DetailViewController;
@class MasterViewController;
@protocol MasterViewControllerDelegate
- (void)SelectionChanged:(NSString *)url;
@end
@interface MasterViewController : UITableViewController
@property (nonatomic, weak) id<MasterViewControllerDelegate> delegate;
@property (strong, nonatomic) DetailViewController *detailViewController;
@end
Then in my MasterViewController.m I'm synthesizing the delegate:
@synthesize delegate;
And finally I'm calling the delegate method from my didSelectRowAtIndexPath method like so:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *links = [NSArray arrayWithObjects:
@"http://www.link1.com",
@"http://www.link2.com",
@"http://www.link3.com",
nil];
[self.delegate SelectionChanged:[links objectAtIndex: indexPath.row]];
}
Then in my DetailViewController.h I have:
@interface DetailViewController : UIViewController <UISplitViewControllerDelegate, MasterViewControllerDelegate>
And in DetailViewController.m:
- (void)SelectionChanged:(NSString *)url {
NSLog(@"URL is %@", url);
}
When I run the app, the NSLog
from SelectionChanged
is never called and I get no errors. Any ideas?
回答1:
Okay I figured it out... In my AppDelegate.m file I added the following to didFinishLaunchingWithOptions
DetailViewController *detail = (DetailViewController *)navigationController.topViewController;
UINavigationController *masterNavigationController = [splitViewController.viewControllers objectAtIndex:0];
MasterViewController *master = (MasterViewController *)masterNavigationController.topViewController;
NSLog(@"%@",masterNavigationController.topViewController);
master.delegate = detail;
So the whole method looks like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
splitViewController.delegate = (id)navigationController.topViewController;
DetailViewController *detail = (DetailViewController *)navigationController.topViewController;
UINavigationController *masterNavigationController = [splitViewController.viewControllers objectAtIndex:0];
MasterViewController *master = (MasterViewController *)masterNavigationController.topViewController;
NSLog(@"%@",masterNavigationController.topViewController);
master.delegate = detail;
return YES;
}
Basically the problem is that I wasn't assigning the delegate anywhere.... duh.
来源:https://stackoverflow.com/questions/8766708/delegate-in-uisplitview-not-being-called