swift实现悬浮球(2024-08)

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

1.封装代码FloatingBallDelegate

2.调用

3.运行测试

一,FloatingBallDelegate封装的悬浮球

bash 复制代码
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主界面控制层

bash 复制代码
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.修改悬浮球不超出屏幕边界

bash 复制代码
    @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.修改图片的大小,悬浮球进入界面的默认位置,右下方

bash 复制代码
 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封装到一个公共调用类文件即可

bash 复制代码
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()
    }
}

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

相关推荐
重生之我在20年代敲代码2 分钟前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
爱上语文4 分钟前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
编程零零七2 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
2401_858286113 小时前
52.【C语言】 字符函数和字符串函数(strcat函数)
c语言·开发语言
铁松溜达py3 小时前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
everyStudy3 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript
C-SDN花园GGbond5 小时前
【探索数据结构与算法】插入排序:原理、实现与分析(图文详解)
c语言·开发语言·数据结构·排序算法
迷迭所归处6 小时前
C++ —— 关于vector
开发语言·c++·算法
架构文摘JGWZ6 小时前
Java 23 的12 个新特性!!
java·开发语言·学习
leon6256 小时前
优化算法(一)—遗传算法(Genetic Algorithm)附MATLAB程序
开发语言·算法·matlab