iOS 实现 弹出侧边栏

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值