swift实现悬浮球(2024-08)

此文章描述如何在swift语言上,实现悬浮球的功能;

1.封装代码FloatingBallDelegate

2.调用

3.运行测试

一,FloatingBallDelegate封装的悬浮球

import UIKit

protocol FloatingBallDelegate: AnyObject {
    func floatingBallTapped()
    func floatingBallDragged(to point: CGPoint)
}

class FloatingBallView: UIView {
    
    weak var delegate: FloatingBallDelegate?
    
    private var circleButton: UIButton!
    private var startPoint: CGPoint = .zero
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        let diameter: CGFloat = 50
        self.frame = CGRect(x: 20, y: 100, width: diameter, height: diameter)
        self.layer.cornerRadius = diameter / 2
        self.backgroundColor = UIColor.blue.withAlphaComponent(0.8)
        
        circleButton = UIButton(type: .custom)
        circleButton.frame = CGRect(x: 0, y: 0, width: diameter, height: diameter)
        circleButton.setTitle("Tap", for: .normal)
        circleButton.setTitleColor(.white, for: .normal)
        circleButton.addTarget(self, action: #selector(circleButtonTapped), for: .touchUpInside)
        self.addSubview(circleButton)
        
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(dragged(_:)))
        self.addGestureRecognizer(panGesture)
    }
    
    @objc private func circleButtonTapped() {
        delegate?.floatingBallTapped()
    }
    
    @objc private func dragged(_ gesture: UIPanGestureRecognizer) {
        let translation = gesture.translation(in: self.superview)
        
        switch gesture.state {
        case .began:
            startPoint = self.center
        case .changed:
            self.center = CGPoint(x: startPoint.x + translation.x, y: startPoint.y + translation.y)
            delegate?.floatingBallDragged(to: self.center)
        default:
            break
        }
    }
}

二,ProductionView主界面控制层

class ProductionView: UIView, FloatingBallDelegate {
    
    private var floatingBall: FloatingBallView!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFloatingBall()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupFloatingBall()
    }
    
    private func setupFloatingBall() {
        floatingBall = FloatingBallView()
        floatingBall.delegate = self
        self.addSubview(floatingBall)
    }
    
    func floatingBallTapped() {
        print("Floating ball tapped!")
        // 处理悬浮球点击事件
        delegate?.searchButtonClicked()
    }
    
    func floatingBallDragged(to point: CGPoint) {
        print("Floating ball dragged to \(point)")
        // 处理悬浮球拖拽事件
    }
}

三:测试,完成!

如果要把悬浮球的文本改成图片,以及,悬浮球不超出内容区域(顶部标题,底部导航栏,和左右两边)。可以修改如下代码。

1.修改悬浮球不超出屏幕边界

    @objc private func dragged(_ gesture: UIPanGestureRecognizer) {
        guard let superview = self.superview else { return }
        
        let translation = gesture.translation(in: superview)
        var newX = self.center.x + translation.x
        var newY = self.center.y + translation.y
        
        // 边界检查,确保悬浮球不会移动到屏幕外
        let halfWidth = self.bounds.width / 2
        let halfHeight = self.bounds.height / 2
        
        let statusBarHeight = UIApplication.shared.statusBarFrame.height+47
        let bottomPadding: CGFloat = 90
        
        let minY = statusBarHeight + halfHeight
        let maxY = superview.bounds.height - bottomPadding - halfHeight
        
        newX = max(halfWidth, min(superview.bounds.width - halfWidth, newX))
        newY = max(minY, min(maxY, newY))
        
        switch gesture.state {
        case .changed:
            self.center = CGPoint(x: newX, y: newY)
            delegate?.floatingBallDragged(to: self.center)
        default:
            break
        }
        
        gesture.setTranslation(.zero, in: superview)
    }

2.修改图片的大小,悬浮球进入界面的默认位置,右下方

 private func setupView() {
        let diameter: CGFloat = 80
        self.frame = CGRect(x:screenWidth-80, y: screenHeight-220, width: diameter, height: diameter)
        self.layer.cornerRadius = diameter / 2
        self.backgroundColor = UIColor(hexString: "#3d9dff", transparency: 1.0)
        
        circleButton = UIButton(type: .custom)
        circleButton.frame = CGRect(x: 0, y: 0, width: diameter, height: diameter)
        
        if let tapImage = UIImage(named: "queryAll") {
            let imageSize = CGSize(width: 39, height: 39)  // Desired image size
            if let resizedImage = tapImage.resized(to: imageSize) {
                circleButton.setImage(resizedImage, for: .normal)
            } else {
                circleButton.setImage(tapImage, for: .normal)  // Fallback to original image
            }
            
            circleButton.imageView?.contentMode = .scaleAspectFit
        }
        
        circleButton.addTarget(self, action: #selector(circleButtonTapped), for: .touchUpInside)
        self.addSubview(circleButton)
        
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(dragged(_:)))
        self.addGestureRecognizer(panGesture)
    }

resized封装到一个公共调用类文件即可

extension UIImage {
    func resized(to newSize: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.main.scale)
        defer { UIGraphicsEndImageContext() }
        self.draw(in: CGRect(origin: .zero, size: newSize))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

此篇文章阐述到此,欢迎各位阅读,一同进步!让我们下一次更好的更新优质的博客。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值