swiftrx-swift

How to get change the value of the UISlider


How to get the values while moving the UISlider?

I'm using the following code:

ViewModel:

import Foundation
import RxSwift

final class ViewModel {

    private let disposeBag = DisposeBag()

    var value: Variable<Float>

    init() {

        self.value = Variable(Float(0.0))

    }
}

ViewController:

@IBOutlet var slider: UISlider!

private var viewModel: ViewModel!
private let disposeBag = DisposeBag()

override func viewDidLoad() {
    viewModel = ViewModel()

    slider.rx.value
        .subscribe(onNext: { (value) in
            self.viewModel.value = Variable(Float(value))
        })
        .addDisposableTo(disposeBag) 
}

But this code does not work. What's my mistake?


Solution

  • Not tested, but I would try:

    override func viewDidLoad() {
        viewModel = ViewModel()
    
        slider.rx.value
            .subscribe(onNext: { (value) in
                self.viewModel.value.value = Float(value) 
            })
            .addDisposableTo(disposeBag) 
    }
    

    Also I would rename your value property in your viewModel to sliderValue (or whatever, but not value). If you do this, your code will look better:

    self.viewModel.sliderValue.value = Float(value)

    instead of

    self.viewModel.value.value = ...