【问题标题】:iOS Master-Detail app: defining protocol, delegatesiOS Master-Detail 应用程序:定义协议、委托
【发布时间】:2012-05-16 20:15:07
【问题描述】:

In the master-detail application template (using ARC, storyboards) in XCode 4.3.2, I am trying to change (more specifically replace) the detail view when an item in master table view is selected.我正在尝试为此实现委托/协议。

我感到困惑的是——哪个类应该实现协议中定义的方法——主控还是细节?

让详细视图实现协议方法对我来说很有意义,因为我将根据选择在详细视图中推送/弹出视图控制器(通过协议方法作为字符串从 master 传递)。

这是我尝试过的

1) 在 MasterViewController.h 中定义协议

@protocol MasterViewDelegate <NSObject>
- (void)masterSelectionChanged:(NSString *)selection;
@end
@interface MasterViewController:UIViewContoller
@property (nonatomic, weak) id <MasterViewDelegate> delegate

2) 在 MasterViewController.m 中

@synthesize delegate;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [delegate masterSelectionChanged:@"Some string based on indexPath.row"];
}

3) 在 DetailViewController.h 中

#import "MasterViewController.m"
@interface DetailViewController:UINavigationController <MasterViewDelegate>
@end

4) 在 DetailViewController.m 中

#pragma mark - MasterViewDelegate
- (void)masterSelectionChanged:(NSString *)selection
{
    NSLog(@"the selection is: %s", selection);
    // WIll push/pop view over here, may be perform segues based on selection
}

在这个过程中,在选择主表中的行时,什么都没有发生。没有崩溃,没有日志显示,构建时也没有错误。我在这里错过了什么?

【问题讨论】:

  • 1) 你说的是 iPad 还是 iPhone(主/细节模板在每个中都非常不同) 2) 你是否真的在任何地方设置了委托属性,或者只是定义了它?
  • @jrturton - 我正在为 iPad 尝试这个。定义delegate 属性??可能这就是我错过的。我应该在哪里定义委托属性?

标签: xcode delegates master-detail uistoryboard


【解决方案1】:

您需要设置委托属性 - 目前它将为零,因此当您向其发送消息时不会发生任何事情。在 iPad 模板中,您可以在详细视图控制器的 viewDidLoad 中执行以下操作:

[super viewDidLoad];
if (self.splitViewController) // Means this won't be called if you use this code on iPhone too.
{
    // According to comments your master controller is embedded in a nav controller
    UINavigationController *nav = (UINavigationController*)[self.splitViewController.viewControllers objectAtIndex:0];
    // I am assuming it is the root view controller
    MasterViewController *master = (MasterViewController*)nav.rootViewController;
    // Finally set the delegate
    master.delegate = self;
}  

【讨论】:

  • 我试过了,但是协议中定义的方法仍然没有被调用。选择行时,委托为 nil。
  • 如果您在我上面的代码中的分配之后登录 master.delegate 会发生什么?:NSLog(@"master : %@ delegate: %@ self: %@",master,master.delegate,self);
  • 它显示 - master: &lt;UINavigationController: xx&gt; delegate: &lt;DetailViewController: xx&gt; self: &lt;DetailViewController: xx&gt;
  • 啊!您的主视图控制器嵌入在导航控制器中。然后,您需要获取指向实际控制器本身的指针 - 大概是导航控制器的 rootViewController
  • @jrjurton - 我也玩过这里的解决方案,效果很好stackoverflow.com/q/10019422/206613
猜你喜欢
  • 2021-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多