美文网首页
swift 悬浮按钮

swift 悬浮按钮

作者: FMaarten | 来源:发表于2019-09-27 10:44 被阅读0次

效果如下:


案例.png

创建悬浮按钮代码如下:

//
//  WYFloatButton.swift
//
//  Created by 王玉 on 2019/8/29.
//  Copyright © 2019 Wiscom. All rights reserved.
//

import UIKit

// 声明协议
@objc protocol FloatDelegate :NSObjectProtocol{
    
    @objc optional func singleClick()
    
    @objc optional func repeatClick()

}

class WYFloatButton: UIButton {

    // 是否可拖拽
    var isDragEnable: Bool = true
    
    // 拖拽后是否自动移到边缘
    var isAbsortEnable: Bool = true
    
    // 背景颜色
    var bgColor: UIColor? = UIColor.green
    
    // 正常情况下 透明度
    var alphaOfNormol: CGFloat = 0.2
    
    // 拖拽时的透明度
    var alphaOfDrag: CGFloat = 0.8
    
    // 圆角大小
    var radiuOfButton: CGFloat = 12
    
    // 拖拽结束后的等待时间
    var timeOfWait: CGFloat = 1.5
    
    // 拖拽结束后的过渡动画时间
    var timeOfAnimation: CGFloat = 0.3
    
    // 按钮距离边缘的内边距
    var paddingOfbutton: CGFloat = 2
    
    // 代理
    var delegate: FloatDelegate? = nil
    
    // 计时器
    fileprivate var timer: Timer? = nil
    
    // 内部使用 起到数据传递的作用
    fileprivate var allPoint: CGPoint? = nil
    
    // 内部使用
    fileprivate var isHasMove: Bool = false
    
    fileprivate var isFirstClick: Bool = true
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = self.bgColor
        self.alpha =  self.alphaOfNormol
        self.layer.cornerRadius = self.radiuOfButton
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.alpha = self.alphaOfDrag
        // 计时器取消
        self.timer?.invalidate()
        // 不可拖拽则退出执行
        if !isDragEnable {
            return
        }
        self.allPoint = touches.first?.location(in: self)
        if touches.first?.tapCount == 1  {
            self.perform(#selector(singleClickMethod), with: nil, afterDelay: 0.2)
        } else if touches.first?.tapCount == 2 {
            self.perform(#selector(repeatClickMethod))
        }
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.isHasMove = true
        if self.isFirstClick {
            NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(singleClickMethod), object: nil)
            self.isFirstClick = false
        }
        if !isDragEnable {
            return
        }
        let temp = touches.first?.location(in: self)
        // 计算偏移量
        let offsetx = (temp?.x)! - (self.allPoint?.x)!
        let offsety = (temp?.y)! - (self.allPoint?.y)!
        self.center = CGPoint.init(x: self.center.x + offsetx, y: self.center.y + offsety)
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.isFirstClick = true
        self.timer = Timer.init(timeInterval: TimeInterval(self.timeOfWait), repeats: false, block: { (Timer) in
            // 过渡
            UIView.animate(withDuration: TimeInterval(self.timeOfAnimation), animations: {
                self.alpha = self.alphaOfNormol
            })
        })
        // 这段代码只有在按钮移动后才需要执行
        if self.isHasMove && isAbsortEnable && self.superview != nil {
            // 移到父view边缘
            let marginL = self.frame.origin.x
            let marginT = self.frame.origin.y
            let superFrame = self.superview?.frame
            let tempy = (superFrame?.height)! - 2 * self.frame.height - self.paddingOfbutton
            let tempx = (superFrame?.width)! - self.frame.width - self.paddingOfbutton
            let xOfR = (superFrame?.width)! - self.frame.width - self.paddingOfbutton
            UIView.animate(withDuration: 0.2, animations: {
                var x = self.frame.origin.x
                if marginT < self.frame.height + self.paddingOfbutton {
                    // 靠顶部
                    if x > tempx {
                        x = tempx
                    }
                    if x < self.paddingOfbutton {
                        x = self.paddingOfbutton
                    }
                    self.frame = CGRect.init(x: x, y: self.paddingOfbutton, width: self.frame.width, height: self.frame.height)
                } else if marginT > tempy {
                    // 靠底部
                    if x > tempx {
                        x = tempx
                    }
                    if x < self.paddingOfbutton {
                        x = self.paddingOfbutton
                    }
                    let y = tempy + self.frame.height
                    self.frame = CGRect.init(x: x, y: y, width: self.frame.width, height: self.frame.height)
                } else if marginL > ((superFrame?.width)! / 2) {
                    // 靠右移动
                    self.frame = CGRect.init(x: xOfR, y: marginT, width: self.frame.width, height: self.frame.height)
                } else {
                    // 靠左移动
                    self.frame = CGRect.init(x: self.paddingOfbutton, y: marginT, width: self.frame.width, height: self.frame.height)
                }
            })
        }
        self.isHasMove = false
        // 将计时器加入runloop
        if let temptime = self.timer {
            RunLoop.current.add(temptime, forMode: .commonModes)
        }
    }
    
    @objc func singleClickMethod() {
        if self.delegate != nil && self.delegate!.responds(to: #selector(FloatDelegate.singleClick)){
            self.delegate?.singleClick!()
        }
    }
    
    @objc func repeatClickMethod() {
        if self.delegate != nil && self.delegate!.responds(to: #selector(FloatDelegate.repeatClick)){
            self.delegate?.repeatClick!()
        }
    }
}

使用方法:

import UIKit

class CustomViewController: UIViewController,FloatDelegate{

    override func viewDidLoad() {
        super.viewDidLoad()

        let frame = CGRect.init(x: 3, y: 100, width: 45, height: 45)
        let floatBtn = WYFloatButton.init(frame: frame)
        floatBtn.delegate = self
        self.view.addSubview(floatBtn)
        floatBtn.backgroundColor = UIColor.init(displayP3Red: 0/255, green: 175.0/255, blue: 171.0/255, alpha: 1)
    }

    // 实现FloatDelegate代理方法
    func singleClick() {
        print("单击")
    }
    func repeatClick() {
        print("双击")
    }
}

相关文章

网友评论

      本文标题:swift 悬浮按钮

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