SwiftUI: How to get continuous updates from Slider

后端 未结 6 1751
悲哀的现实
悲哀的现实 2020-12-11 01:56

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

struct MyView: View {

    @State private var value = 0.5

    var body: some View {
               


        
6条回答
  •  独厮守ぢ
    2020-12-11 02:20

    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()
    
      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()))
    

提交回复
热议问题