美文网首页
类似assistive touch实现的方法

类似assistive touch实现的方法

作者: 张俊凯 | 来源:发表于2018-07-23 16:19 被阅读8次

    需求

    按钮跟随手指移动,松开后停留在最左边和最右边,顶部挨着状态栏,顶部挨着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

    相关文章

      网友评论

          本文标题:类似assistive touch实现的方法

          本文链接:https://www.haomeiwen.com/subject/qsdjmftx.html