SwiftUI:如何从Slider获取连续更新 [英] SwiftUI: How to get continuous updates from Slider
问题描述
我正在尝试像这样的SwiftUI和Slider控件:
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
}
}
}
我试图在用户拖动Slider
时从其不断获取更新,但是看来它仅在值更改结束时更新值.
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.
有人玩过这个吗?知道如何让SwiftUI滑块发布价值变化流?结合起来吗?
Anyone played with this? know how to get a SwiftUI Slider to issue a stream of value changes? Combine perhaps?
推荐答案
在SwiftUI中,您可以将UI元素(例如,滑块)绑定到数据模型中的属性,并在那里实现业务逻辑.
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)
}
}
请注意,要使场景使用数据模型对象,您需要将window.rootViewController
更新为SceneDelegate类中的以下内容,否则应用程序将崩溃.
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()))
这篇关于SwiftUI:如何从Slider获取连续更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!