adamcampbell
adamcampbell

Reputation: 53

(SwiftUI) Bind Slider and TextField to the same variable?

I was wondering if it was possible to bind a Slider and a TextField to the same variable? The reasoning is that I want the user to be able to populate a value by either sliding the slider, or manually entering the value into the text field.

Doing either should also update the other method, for example if the user slides the slider to a value of 100, then the textfield should live update to display 100.

Is this possible, and if not then are there any similar solutions which may provide a similar result?

Upvotes: 2

Views: 1514

Answers (1)

Obliquely
Obliquely

Reputation: 7072

Yes, it's possible. The following code shows how to do the binding of a value to two different controls. (To make this code usable, you'd need to do some validation on the TextField to limit the range however.)

import SwiftUI

class Model : ObservableObject {

      @Published var value : Double = 50
}

struct ContentView: View {

      @ObservedObject var model = Model()

      var body: some View {

            let formatter = NumberFormatter()
            formatter.numberStyle = NumberFormatter.Style.decimal
            formatter.roundingMode = NumberFormatter.RoundingMode.halfUp
            formatter.maximumFractionDigits = 0
            //formatter.minimumFractionDigits = 2

            let spellOutFormatter = NumberFormatter()
            spellOutFormatter.numberStyle = .spellOut

            return Form() {
                  Text("Number as words: \(spellOutFormatter.string(from: NSNumber(value: model.value)) ?? "Not Known")")

                  TextField("Number", value: $model.value, formatter: formatter)

                  Slider(value: $model.value, in: 0...100, step: 1).padding()
            }
      }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Upvotes: 6

Related Questions