SwiftUI: How to get continuous updates from Slider

2020-02-07 01:10发布

I'm experimenting with SwiftUI and the Slider control like this:

struct MyView: View {

    @State private var value = 0.5

    var body: some View {
        Slider(value: $value) { pressed in
        }
    }
}

I'm trying to get continuous updates from the Slider as the user drags it, however it appears that it only updates the value at the end of the value change.

Anyone played with this? know how to get a SwiftUI Slider to issue a stream of value changes? Combine perhaps?

3条回答
迷人小祖宗
2楼-- · 2020-02-07 01:26

After much playing around I ended up with the following code. It's a little cut down to keep the answer short, but here goes. There was a couple of things I needed:

  • To read value changes from the slider and round them to the nearest integer before setting an external binding.
  • To set a localized hint value based on the integer.
struct AspectSlider: View {

    // The first part of the hint text localization key.
    private let hintKey: String

    // An external integer binding to be set when the rounded value of the slider
changes to a different integer.
    private let value: Binding<Int>

    // A local binding that is used to track the value of the slider.
    @State var sliderValue: Double = 0.0

    init(value: Binding<Int>, hintKey: String) {
        self.value = value
        self.hintKey = hintKey
    }

    var body: some View {
        VStack(alignment: .trailing) {

            // The localized text hint built from the hint key and the rounded slider value.
            Text(LocalizedStringKey("\(hintKey).\(self.value.value)"))

            HStack {
                Text(LocalizedStringKey(self.hintKey))
                Slider(value: Binding<Double>(
                    getValue: { self.$sliderValue.value },
                    setValue: { self.sliderChanged(toValue: $0) }
                    ),
                    through: 4.0) { if !$0 { self.slideEnded() } }
            }
        }
    }

    private func slideEnded() {
        print("Moving slider to nearest whole value")
        self.sliderValue = self.sliderValue.rounded()
    }

    private func sliderChanged(toValue value: Double) {
        $sliderValue.value = value
        let roundedValue = Int(value.rounded())
        if roundedValue == self.value.value {
            return
        }

        print("Updating value")
        self.value.value = roundedValue
    }
}
查看更多
Luminary・发光体
3楼-- · 2020-02-07 01:26

I am not able to reproduce this issue on iOS 13 Beta 2. Which operating system are you targeting?

Using a custom binding, the value is printed for every small change, not only after editing ended.

Slider(value: Binding<Double>(getValue: {0}, setValue: {print($0)}))

Note, that the closure ({ pressed in }) only reports when editing end starts and ends, the value stream is only passed into the binding.

查看更多
SAY GOODBYE
4楼-- · 2020-02-07 01:35

In SwiftUI, you can bind UI elements such as slider to properties in your data model and implement your business logic there.

For example, to get continuous slider updates:

import SwiftUI
import Combine

final class SliderData: BindableObject {

  let didChange = PassthroughSubject<SliderData,Never>()

  var sliderValue: Float = 0 {
    willSet {
      print(newValue)
      didChange.send(self)
    }
  }
}

struct ContentView : View {

  @EnvironmentObject var sliderData: SliderData

  var body: some View {
    Slider(value: $sliderData.sliderValue)
  }
}

Note that to have your scene use the data model object, you need to update your window.rootViewController to something like below inside SceneDelegate class, otherwise the app crashes.

window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(SliderData()))

enter image description here

查看更多
登录 后发表回答