Search code examples
iosswiftcustom-controlsuislider

Sluggish response from custom slider


I am trying to create a custom slider that uses a UIButton as the thumb. Since I can't seem to find a way to use a UIView as the thumb in a slider, I decided to build a custom one. However, when I run it, the thumb is sluggish to respond on the initial drag. The following is the code so far. The gif below is running slower than actual speed but illustrates the point.

import Foundation
import UIKit

class CustomSlider: UIView, UIGestureRecognizerDelegate {
    let buttonView = UIButton()
    var minimumPosition = CGPoint()
    var maximumPosition = CGPoint()
    var originalCenter = CGPoint()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    func commonInit() {
        // add a pan recognizer
        let recognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(recognizer:)))
        recognizer.delegate = self
        addGestureRecognizer(recognizer)

        backgroundColor = UIColor.green

        buttonView.frame = CGRect(x: 0, y: 0, width: bounds.height, height: bounds.height)
        buttonView.backgroundColor = UIColor.purple
        self.addSubview(buttonView)

        minimumPosition = CGPoint(x:buttonView.frame.width / 2, y: 0)
        maximumPosition = CGPoint(x: bounds.width - buttonView.frame.width / 2, y: 0)
    }

    @objc func handlePan(recognizer: UIPanGestureRecognizer) {
        if recognizer.state == .began {
            originalCenter = buttonView.center
        }
        if recognizer.state == .changed {
            let translation = recognizer.translation(in: self)
            let newX = originalCenter.x + translation.x
            buttonView.center = CGPoint(x: min(maximumPosition.x, max(minimumPosition.x, newX)), y: buttonView.frame.midY)
        }
    }
}

sluggish_thumb


Solution

  • Finally figured it out. It only happens in the iPhone XR simulator. Tried the iPhone XS, among others, and they were smooth as glass.