问题描述
我正在试验 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 Slider 发出值变化流吗?也许结合?
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)
}
}
请注意,要让您的场景使用数据模型对象,您需要在 SceneDelegate 类中将 window.rootViewController
更新为如下所示的内容,否则应用程序会崩溃.
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 获取持续更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!