类似assistive touch实现的方法

需求

按钮跟随手指移动,松开后停留在最左边和最右边,顶部挨着状态栏,顶部挨着tabbar


12312312.gif

实现思路

视图添加平移手势,移动过程中即时改变视图的位置,结束后判断停留位置进行悬停

代码

 UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(touchPan:)];
    [button addGestureRecognizer:panGestureRecognizer];
- (void)touchPan:(UIPanGestureRecognizer*)recognizer{
    
    UIView *touchView = recognizer.view;
    
    //拿到变化后的点 即时更新视图的位置
    CGPoint translation = [recognizer translationInView:self.view];
    CGFloat centerX = touchView.center.x + translation.x;
    CGFloat centerY = touchView.center.y+ translation.y;
    touchView.center = CGPointMake(centerX,centerY);
    //位移清零 让按钮只移动变化的量
    [recognizer setTranslation:CGPointZero inView:self.view];
    
    
    CGFloat ScreenWidth = [[UIScreen mainScreen] bounds].size.width;
    CGFloat ScreenHeight = [[UIScreen mainScreen] bounds].size.height;
    CGFloat finalCenterX;
    CGFloat finalCenterY = centerY;
    CGFloat touchViewCenterX = touchView.frame.size.width * 0.5;
    CGFloat touchViewCenterY = touchView.frame.size.height * 0.5;
    //结束后做左右上下悬浮处理
    if(recognizer.state == UIGestureRecognizerStateEnded|| recognizer.state == UIGestureRecognizerStateCancelled) {
        
        if(centerX > ScreenWidth * 0.5) {//停留右边
            
            finalCenterX = ScreenWidth - touchViewCenterX;
            
        }else{//停留左边
            
            finalCenterX = touchViewCenterX;
            
        }
        
        //固定最高和最低的位置
        if (centerY < touchViewCenterY + 20) {//顶部留出状态栏的位置
            finalCenterY = touchViewCenterY + 20;
        }
        
        if (centerY > ScreenHeight - 49) {//底部留出tabbar的位置
            finalCenterY = ScreenHeight - 49 - touchViewCenterY;
        }
        
        
        [UIView animateWithDuration:0.3 animations:^{
            
            touchView.center = CGPointMake(finalCenterX,finalCenterY);
            
        }];
        
    }
    
}

参考链接:https://www.jianshu.com/p/29481c868774?open_source=weibo_search

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,009评论 3 119
  • 1.一个星期前打电话调了架构,上午从新打客服电话查了我的架构!帮助亲推2代订产品下单!她说她一直都买不了,我也找不...
    雪儿68阅读 102评论 0 0