iOS添加边缘手势( UIScreenEdgePanGestureRecognizer)实现侧滑效果

本文介绍如何在iOS应用中实现边缘侧滑手势效果,包括手势识别与响应、动画过渡等关键技术点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过添加边缘手势来实现侧滑的效果,类似于qq界面的边缘侧滑 ,亦或广告界面的侧滑

@interface中定义一个全局view

@property(nonatomic,weak)UIView *adView;

添加侧滑手势

// 添加边缘手势
    UIScreenEdgePanGestureRecognizer *ges = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(showAd:)];
    // 指定左边缘滑动
    ges.edges = UIRectEdgeLeft;
    [self.view addGestureRecognizer:ges];
    // 如果ges的手势与collectionView手势都识别的话,指定以下代码,代表是识别传入的手势
    [self.collectionView.panGestureRecognizer requireGestureRecognizerToFail:ges];

实现滑出方法

- (void)showAd:(UIScreenEdgePanGestureRecognizer *)ges {
    // 让view跟着手指去移动
    // frame的x应该为多少??应该获取到手指的x值
    // 取到手势在当前控制器视图中识别的位置
    CGPoint p = [ges locationInView:self.view];
    NSLog(@"%@", NSStringFromCGPoint(p));
    CGRect frame = self.adView.frame;
    // 更改adView的x值. 手指的位置 - 屏幕宽度
    frame.origin.x = p.x - [UIScreen mainScreen].bounds.size.width;
    // 重新设置上去
    self.adView.frame = frame;

    if (ges.state == UIGestureRecognizerStateEnded || ges.state == UIGestureRecognizerStateCancelled) {
        // 判断当前广告视图在屏幕上显示是否超过一半
        if (CGRectContainsPoint(self.view.frame, self.adView.center)) {
            // 如果超过,那么完全展示出来
            frame.origin.x = 0;
        }else{
            // 如果没有,隐藏
            frame.origin.x = -[UIScreen mainScreen].bounds.size.width;
        }
        [UIView animateWithDuration:0.25 animations:^{
            self.adView.frame = frame;
        }];
    }   
}
/**
 *  添加滑出的view
 */
- (void)setupAdView {
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    // 设置背景颜色
    view.backgroundColor = [UIColor randomColor];
    CGRect frame = view.frame;
    // 将x值改成负的屏幕宽度,原因是因为默认就在屏幕的左边
    frame.origin.x = -view.frame.size.width;
    // 设置给view
    view.frame = frame;
    // 因为该view是盖在所有的view身上,所以应该添加到window上
    [[UIApplication sharedApplication].keyWindow addSubview:view];
    self.adView = view;

    // 添加轻扫手势  -- 滑回
    UISwipeGestureRecognizer *ges = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(closeAd)];
    ges.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.adView addGestureRecognizer:ges];
}

这是回滑的方法

- (void)closeAd {
    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = self.adView.frame;
        frame.origin.x = -[UIScreen mainScreen].bounds.size.width;
        self.adView.frame = frame;
    }];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值