【问题标题】:Creating a delegate to change views from a menu创建委托以从菜单更改视图
【发布时间】:2013-07-04 10:29:38
【问题描述】:

我希望能够将视图控制器从我的自定义菜单推送到我的主要子类导航控制器,并且我想使用委托来实现。在我尝试更改视图控制器之前,我尝试了一些更简单的方法,即更改当前视图控制器标题。 这是我到目前为止编写的代码,但在 TableView 单元格上点击不会触发委托。 (或者看起来)

请指教

 -> RootViewController
                 / \
            集装箱集装箱
                | |
     SlideMenuViewController 子类 UINavigationController
                | | | | |
     UITableViewController VC1 VC2 VC3 VC4


SlideMenuViewController.h:

@protocol SlidingMenuDelegate <NSObject>

@end

@interface SlideMenuViewController : UIViewController
{
        id <SlidingMenuDelegate> delegate;
}
@property (strong, nonatomic) id delegate;

SlideMenuViewController.m:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //do something to send controller

    ((UIRTLNavigationController *)(self.delegate)).titleForView.text = @"test";
}

MyNavigationController.h:

@interface MyNavigationController : UINavigationController <UINavigationControllerDelegate>

@property (nonatomic, strong) UILabel *titleForView;

MyNavigationController.m:

- (void)showRightMenu
{
...
...
//Some animation to slide the menu out

    //Delegate stuff
    //Get the storyboard's instance.
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:[NSBundle mainBundle]];

    SlideMenuViewController *slideMenuVC;

    //Get the viewcontrollers instance from the storyboard's instance
    slideMenuVC = [storyBoard instantiateViewControllerWithIdentifier:@"slideMenuSID"];
    slideMenuVC.delegate = self;
}

【问题讨论】:

  • 委托在哪里设置?为什么协议没有任何方法定义?委托属性通常不应该是strong。调试或添加一些日志记录代码以查看选择表格单元格时发生的情况。

标签: ios objective-c cocoa-touch ios5 delegates


【解决方案1】:

您的SlidingMenuDelegate 协议需要一些(可选)方法,例如slidingMenu:didSelectOption:。另外,我会定义一个枚举或其他东西来指定菜单提供的所有选项。

然后在你的 tableView:didSelectRowAtIndexPath: 方法中,你会这样做

if ([self.delegate respondsToSelector:@selector(slidingMenu:didSelectOption:)]) {
    SlidingMenuOption option;

    switch (indexPath.row) {
    case 0:
        option = SlidingMenuFooOption;
        break;

    case 1:
        option = SlidingMenuBarOption;
        break;

    // ...
    }

    [self.delegate slidingMenu:self didSelectOption:option];
}

最后,您的代理会响应此slidingMenu:didSelectOption: 消息(例如设置导航控制器的标题)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2018-04-05
    • 2013-12-20
    • 2014-12-08
    • 2021-03-12
    相关资源
    最近更新 更多