How to enable “tap and slide” in a UISlider?

后端 未结 14 543
不知归路
不知归路 2020-12-03 20:54

What I want to get is a UISlider which lets the user not only slide when he starts on its thumbRect, but also when he taps elsewhere. When the user

14条回答
  •  北海茫月
    2020-12-03 21:42

    Here is my solution that works :

    import UIKit
    
    class CustomSlider: UISlider {
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupView()
        }
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setupView()
        }
        
        
        private func setupView() {
            addTapGesture()
        }
        
        private func addTapGesture() {
            let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
            addGestureRecognizer(tap)
        }
        
        @objc private func handleTap(_ sender: UITapGestureRecognizer) {
            let location = sender.location(in: self)
            let percent = minimumValue + Float(location.x / bounds.width) * maximumValue
            setValue(percent, animated: true)
            sendActions(for: .valueChanged)
        }
    }
    

提交回复
热议问题