ios - 从 UIToolbar 子类切换 View Controller

标签 ios iphone objective-c

请原谅我对 IOS 的陌生,但当有人单击我的工具栏中的按钮时,我正试图切换 View Controller 。对于我的工具栏,我覆盖了 UIToolbar 并绘制了我自己的自定义工具栏。我有四个按钮,每个按钮都有自己的操作,如下所示:

NSMutableArray *toolbarItems = [@[] mutableCopy];
[toolbarItems addObject:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notifications"] style:UIBarButtonItemStyleBordered target:self action:@selector(viewNotifications)]];

我希望能够做类似的事情:

-(void)viewNotifications
{
    NSLog(@"CustomUIToolbar::viewNotifications");

    //layoutFlow....

    // Show the notifications view controller
    NotificationsViewController *rootViewController = [[NotificationsViewController alloc] initWithCollectionViewLayout:layoutFlow];

    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
    [self presentViewController:navController animated:YES completion:NULL];
}

这个问题显然是 UIToolbar 不能直接访问切换 View Controller 。有没有办法从自定义 UIToolbar 中访问 presentViewController 方法或类似方法?

最佳答案

创建一个协议(protocol)和一个委托(delegate),并让创建 UIToolBarUIViewController 实现该委托(delegate)。

当用户按下 UIBarButtonItem 时,您向委托(delegate)发送消息(主 UIViewController)并在那里处理 UINavigationController 代码。

@protocol ToolBarProtocol <NSObject>

-(void)didPressButton1;

@end

@property (nonatomic) id <ToolBarProtocol> delegate

在创建 UIToolBar 时:

YourToolBar *toolbar = [YourToolBar alloc] init];
toolbar.delegate = self;

在你的方法中改变以告诉代理应该发生什么:

-(void)viewNotifications
{
    NSLog(@"CustomUIToolbar::viewNotifications");

    //layoutFlow....
    if ([self.delegate respondsToSelector:@selector(didPressButton1)])
    {
        [self.delegate didPressButton1];
    }
}

关于ios - 从 UIToolbar 子类切换 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24803437/

相关文章:

ios - CloudKit - 完整的错误处理示例

iphone - Objective-C 在 dealloc 方法中释放未初始化的类成员

ios - 如何在 UICollectionViewCell 上显示标准复选标记?

ios - 使用*作为Realm中 'LIKE'的常规字符过滤对象

iphone - 如何将 NSIndexPath 转换为 NSInteger?

iphone - 如何在 iTune Connect 上为我的 iPhone 应用程序设置自动续订应用程序内购买?

objective-c - 将 Objective-C 文件编译成目标文件 (.o)

javascript - 单个 html 页面 - html 图表 -

ios - Xcode - 找不到选项 FacebookSDK 的目录

iphone - 检测添加为 UIScrollView subview 的 UIImage 触摸