请原谅我对 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),并让创建 UIToolBar
的 UIViewController
实现该委托(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/