iosswiftslidercgrectsender

Programmed UISlider value not changing


My code uses a programmed slider and I want to find the value in the debug section of Xcode. I am not seeing anything in the debug area except for "ben: 0". If I move the slider to the end of the right section it will say "ben" 1" but that is the only values I am see being changed. This is all code so you can just copy into your Xcode project, no storyboard needed.

import UIKit

class ViewController: UIViewController {
    var move = UISlider()

    override func viewDidLoad() {
        super.viewDidLoad()

        [move].forEach({
            $0.translatesAutoresizingMaskIntoConstraints = false
            self.view.addSubview($0)
        })

        move.frame = CGRect(x: view.center.x-115, y: view.center.y+200, width: 200, height: 30)
        move.addTarget(self, action: #selector(moveRight), for: .valueChanged)
    }

    @objc func moveRight(_ sender: UISlider) {
        let currentValue = Int(sender.value)

        print("ben:",currentValue)
    }
}

Solution

  • First you need to give that slider positioning constraints like top , leading and width as you set $0.translatesAutoresizingMaskIntoConstraints = false which invalidates setting the frame otherwise comment it and leave the frame line

    Second default values for the slider's minimumValue , maximumValue are 0,1 respectively so you need to set them according to what you need


    override func viewDidLoad() {
        super.viewDidLoad() 
    
        self.view.addSubview(move) 
        move.minimumValue = 10 
        move.maximumValue = 50 
        move.frame = CGRect(x: view.center.x-115, y: view.center.y+200, width: 200, height: 30)
        move.addTarget(self, action: #selector(moveRight), for: .valueChanged)
    }
    
    @objc func moveRight(_ sender: UISlider) {
        let currentValue = Int(sender.value)
    
        print("ben:",currentValue)
    }