Search code examples
iosswiftpositionuislider

Get X, Y position of value on UISlider


I am trying to get the X,Y position of a particular value on a UISlider track so I can place a textfield at that location before I even move the slider with my thumb. I want to be able to place multiple textfields along the track showing what value is at that location.

Could anybody help me achieve this?

Thank you


Solution

  • let values: [Float] = [15, 30, 50, 70, 85]
    
    for value in values {
        guard (slider.minimumValue...slider.maximumValue).contains(value) else { continue }
    
        let label = UILabel()
        label.text = "\(value)"
    
        view.addSubview(label)
        label.translatesAutoresizingMaskIntoConstraints = false
    
        let thumbRect = slider.thumbRect(forBounds: slider.bounds,
                                         trackRect: slider.trackRect(forBounds: slider.bounds),
                                         value: value)
    
        let convertedThumbRect = slider.convert(thumbRect, to: view)
    
        NSLayoutConstraint.activate([
            label.centerXAnchor.constraint(equalTo: view.leadingAnchor, constant: convertedThumbRect.midX),
            slider.topAnchor.constraintEqualToSystemSpacingBelow(label.bottomAnchor, multiplier: 1)
        ])
    }