#import "SideMenuViewController.h"
@property (nonatomic, strong) SideMenuViewController *sideMenuViewController;
@property (nonatomic, assign) BOOL isSideMenuVisible;
// 创建侧边菜单视图控制器
self.sideMenuViewController = [[SideMenuViewController alloc] init];
- (void)showSideMenu {
CGFloat sideMenuWidth = 300; // 侧边菜单的宽度
// 获取当前活动的窗口
UIWindow *window = UIApplication.sharedApplication.windows.firstObject;
// 计算侧边菜单的位置和尺寸
CGRect sideMenuFrame = CGRectMake(0,0, sideMenuWidth, CGRectGetHeight(window.bounds) );
self.sideMenuViewController.view.frame = sideMenuFrame;
// 添加遮罩视图
UIView *maskView = [[UIView alloc] initWithFrame:window.bounds];
maskView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5]; // 全透明黑色背景
[window addSubview:maskView];
// 将侧边菜单添加到窗口上
[window addSubview:self.sideMenuViewController.view];
// 动画效果,使侧边菜单从左侧弹出
[UIView animateWithDuration:0.8 animations:^{
CGRect newFrame = CGRectMake(0,0, sideMenuWidth, CGRectGetHeight(window.bounds));
self.sideMenuViewController.view.frame = newFrame;
} completion:^(BOOL finished) {
// 完成动画后执行其他操作
}];
// 添加点击遮罩视图关闭侧边菜单的手势
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideSideMenu)];
[maskView addGestureRecognizer:tapGesture];
// 更新侧边菜单状态
self.isSideMenuVisible = YES;
}
- (void)hideSideMenu {
// 获取当前活动的窗口
UIWindow *window = UIApplication.sharedApplication.windows.firstObject;
CGFloat sideMenuWidth = CGRectGetWidth(self.sideMenuViewController.view.frame);
// 动画效果,使侧边菜单收回到左侧屏幕外
[UIView animateWithDuration:0.3 animations:^{
CGRect newFrame = CGRectMake(-sideMenuWidth, 0, sideMenuWidth, CGRectGetHeight(window.bounds) );
self.sideMenuViewController.view.frame = newFrame;
} completion:^(BOOL finished) {
// 完成动画后移除侧边菜单视图和遮罩视图
[self.sideMenuViewController.view removeFromSuperview];
for (UIView *subview in window.subviews) {
if ([subview isKindOfClass:[UIView class]] && subview.backgroundColor && CGColorEqualToColor(subview.backgroundColor.CGColor, [UIColor colorWithWhite:0 alpha:0.5].CGColor)) {
[subview removeFromSuperview];
break;
}
}
}];
// 更新侧边菜单状态
self.isSideMenuVisible = NO;
}
01-05