SwiftUI - 在 Digital Crown 旋转期间显示视图
Posted
技术标签:
【中文标题】SwiftUI - 在 Digital Crown 旋转期间显示视图【英文标题】:SwiftUI - show view during Digital Crown rotation 【发布时间】:2021-08-11 22:17:31 【问题描述】:我希望在滚动时显示 Text
,但在不滚动时使用 digitalCrownRotation
隐藏文本(如滚动时显示的指示器)。目前,当我滚动时它只能以一种方式工作并且不能很好地工作,这可以实现吗?
extension View
func hidden(_ shouldHide: Bool) -> some View
opacity(shouldHide ? 0 : 1)
struct ContentView: View
@State var date: Date = Date()
@State var scroll: Double = 0.0
@State var previous: Double = 0.0
@State var scrolling: Bool = false
var body: some View
VStack
Text("\(date.dateFormat("E, d MMM"))")
.focusable(true)
.hidden(!scrolling)
.digitalCrownRotation($scroll, from: 0, through: 365, by: 1, sensitivity: .low, isContinuous: false, isHapticFeedbackEnabled: true)
.onChange(of: scroll) value in
scrolling = (value > previous)
previous = value
date = Calendar.current.date(byAdding: .day, value: Int(value), to: Date())!
.onAppear
self.date = Date()
【问题讨论】:
scrolling = value != previous
@TamásSengel 对我不起作用,它必须是双向的,所以对于 digitalCrownRotation
【参考方案1】:
您需要在用户滚动时显示您的视图,并在他结束滚动时隐藏。
我建议您使用来自 Combine 的 .debounce
。它会在每个新值传递后等待一段时间(在我的示例中为 1 秒,这对你来说应该没问题),并且只有在这段时间内没有发送新值时才传递它。
所以在这种情况下,它会在最后一次皇冠触摸后等待 1 秒,然后再隐藏视图:
@State var date: Date = Date()
@State var scroll: Double = 0.0
@State var scrolling: Bool = false
private let relay = PassthroughSubject<Double, Never>()
private let debouncedPublisher: AnyPublisher<Double, Never>
init()
debouncedPublisher = relay
.removeDuplicates()
.debounce(for: 1, scheduler: RunLoop.main)
.eraseToAnyPublisher()
var body: some View
VStack
Text("\(date)")
.focusable(true)
.opacity(scrolling ? 1 : 0)
.digitalCrownRotation($scroll, from: 0, through: 365, by: 1, sensitivity: .low, isContinuous: false, isHapticFeedbackEnabled: true)
.onChange(of: scroll) value in
withAnimation
scrolling = true
relay.send(value)
date = Calendar.current.date(byAdding: .day, value: Int(value), to: Date())!
.onReceive(
debouncedPublisher,
perform: value in
withAnimation
scrolling = false
)
.onAppear
self.date = Date()
结果:
【讨论】:
轻松实现!谢谢你给我看debounce
!!完美运行:D以上是关于SwiftUI - 在 Digital Crown 旋转期间显示视图的主要内容,如果未能解决你的问题,请参考以下文章