Search code examples
swiftxcodeuikit

UISlider ignores starting value


I have a weird behavior from my UISlider. I set it's initial Value and all looks fine in the Interface Builder. But it is ignored when a screen with it appears and my slider starts from a left position . I tried to place a few breakpoints but I can't find anything about it in the debug area. Any advice how to fix or debug it?

enter image description here


Solution

  • Create a IBOutlet like you did for the label and name it durationSlider. Then set the initial values in the viewDidLoad function:

    let duration: Float = 5
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        durationSlider.minimumValue = 0
        durationSlider.maximumValue = duration
        durationSlider.value = 3    // set your startValue here
        
        updateSliderLabel()
    }
    
    @IBAction func durationSliderChanged(_ sender: Any) {
        print("currentValue: \(durationSlider.value)")
        updateSliderLabel()
    }
    
    func updateSliderLabel() {
        durationLabel.text = String(round(durationSlider.value)) + "s"
    }