TSProgressSlider.swift 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. //
  2. // TSProgressSlider.swift
  3. // Pods
  4. //
  5. // Created by 100Years on 2025/4/22.
  6. //
  7. import UIKit
  8. open class TSProgressSlider: UISlider {
  9. // 透明覆盖视图
  10. private let overlayView = UIView()
  11. override init(frame: CGRect) {
  12. super.init(frame: frame)
  13. setupOverlay()
  14. }
  15. required public init?(coder: NSCoder) {
  16. super.init(coder: coder)
  17. setupOverlay()
  18. }
  19. private func setupOverlay() {
  20. // 配置透明覆盖视图
  21. overlayView.backgroundColor = .clear
  22. overlayView.isUserInteractionEnabled = true
  23. addSubview(overlayView)
  24. // 添加拖动手势
  25. let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
  26. overlayView.addGestureRecognizer(panGesture)
  27. // 添加点击手势
  28. let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
  29. overlayView.addGestureRecognizer(tapGesture)
  30. }
  31. open override func layoutSubviews() {
  32. super.layoutSubviews()
  33. // 确保覆盖视图与slider同大小
  34. overlayView.frame = bounds
  35. }
  36. // 处理拖动手势
  37. @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
  38. let location = gesture.location(in: overlayView)
  39. updateSliderValue(with: location)
  40. if gesture.state == .ended {
  41. sendActions(for: .touchUpInside)
  42. }
  43. }
  44. // 处理点击手势
  45. @objc private func handleTap(_ gesture: UITapGestureRecognizer) {
  46. let location = gesture.location(in: overlayView)
  47. updateSliderValue(with: location)
  48. sendActions(for: .touchUpInside)
  49. }
  50. // 更新滑块值
  51. private func updateSliderValue(with location: CGPoint) {
  52. let percentage = max(0, min(1, location.x / bounds.width))
  53. setValue(Float(percentage), animated: false)
  54. sendActions(for: .valueChanged)
  55. }
  56. }