仿苹果的全局浮动按钮——swift

模仿苹果做了一个全局浮动按钮,可以拖拽,可以展开和收缩,自动靠边。实现步骤如下:

1.继承自UIView,重写init方法,在init里添加点击手势和拖动手势。加到appDelegate.window!里,实现全局浮动。

2.定制按钮样式,通过layer层画出五个嵌套的圆。

        let layer = CAShapeLayer()
        layer.path = path.cgPath
        layer.fillColor = UIColor(white: CGFloat(white), alpha: CGFloat(alpha)).cgColor
        layer.strokeColor = UIColor(white: CGFloat(white), alpha: CGFloat(alpha)).cgColor

        self.layer.addSublayer(layer)

3.实现拖拽手势效果:

        switch pan.state {
        case UIGestureRecognizerState.began:
            self.superview?.bringSubview(toFront: self) //拖拽开始
            break
        case UIGestureRecognizerState.changed:
            let point = pan.translation(in: self)
            let f = self.frame
            let dx = point.x + f.origin.x
            let dy = point.y + f.origin.y
            self.frame = CGRect(x: dx, y: dy, width: LYCopyGlobalButton.ButtonSize, height: LYCopyGlobalButton.ButtonSize)//跟随手势完成拖拽效果
            //  注意一旦你完成上述的移动,将translation重置为0十分重要。否则translation每次都会叠加
            pan.setTranslation(CGPoint(x: 0, y: 0), in: self)
            break
        case UIGestureRecognizerState.ended:
            let f = self.frame//拖拽结束,需要靠边
            var dx = f.origin.x
            var dy = f.origin.y
            if dx > superFrame.size.width-10-LYCopyGlobalButton.ButtonSize {
                dx = superFrame.size.width-10-LYCopyGlobalButton.ButtonSize
            } else if dx < 10 {
                dx = 10.0
            } else {
                dx = dx > superFrame.size.width-dx ? superFrame.size.width-10-LYCopyGlobalButton.ButtonSize : 10
            }

            if dy > superFrame.size.height-10-LYCopyGlobalButton.ButtonSize {
                dy = superFrame.size.height-10-LYCopyGlobalButton.ButtonSize
            } else if dy < 10 {
                dy = 10.0
            }//永远靠左右两边,不用管上下
            
            UIView.animate(withDuration: 0.2) {
                self.frame = CGRect(x: dx, y: dy, width: f.size.width, height: f.size.height)
            }
            break
            
        default: break
            
        }
        let point:CGPoint = pan.translation(in: self)

        self.transform = CGAffineTransform.init(translationX: point.x, y: point.y)

4.通过动画效果实现展开缩放效果。

附上代码地址:点击打开链接获取swift代码

猜你喜欢

转载自blog.csdn.net/weixin_42012181/article/details/80680322