1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- //
- // TSProgressSlider.swift
- // Pods
- //
- // Created by 100Years on 2025/4/22.
- //
- import UIKit
- open class TSProgressSlider: UISlider {
- // 透明覆盖视图
- private let overlayView = UIView()
-
- override init(frame: CGRect) {
- super.init(frame: frame)
- setupOverlay()
- }
-
- required public init?(coder: NSCoder) {
- super.init(coder: coder)
- setupOverlay()
- }
-
- private func setupOverlay() {
- // 配置透明覆盖视图
- overlayView.backgroundColor = .clear
- overlayView.isUserInteractionEnabled = true
- addSubview(overlayView)
-
- // 添加拖动手势
- let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
- overlayView.addGestureRecognizer(panGesture)
-
- // 添加点击手势
- let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
- overlayView.addGestureRecognizer(tapGesture)
- }
-
- open override func layoutSubviews() {
- super.layoutSubviews()
- // 确保覆盖视图与slider同大小
- overlayView.frame = bounds
- }
-
- // 处理拖动手势
- @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
- let location = gesture.location(in: overlayView)
- updateSliderValue(with: location)
-
- if gesture.state == .ended {
- sendActions(for: .touchUpInside)
- }
- }
-
- // 处理点击手势
- @objc private func handleTap(_ gesture: UITapGestureRecognizer) {
- let location = gesture.location(in: overlayView)
- updateSliderValue(with: location)
- sendActions(for: .touchUpInside)
- }
-
- // 更新滑块值
- private func updateSliderValue(with location: CGPoint) {
- let percentage = max(0, min(1, location.x / bounds.width))
- setValue(Float(percentage), animated: false)
- sendActions(for: .valueChanged)
- }
- }
|