我正在使用SwiftUI构建一个手表应用程序。出于某种原因,我需要检查用户是否将表冠向上或向下旋转,然后显示或隐藏一些UI。我只找到了这个函数digitalCrownRotation
,它可以读取表冠上的值,但是我还没有弄清楚如何得到旋转方向。
任何提示都将不胜感激。
Updata示例代码我正在使用digitalCrownRotation,但问题是滚动视图现在没有滚动。
struct ContentView: View {
@State private var up = false
@State private var scrollAmount = 0.0
@State private var prevScrollAmount = 0.0
var body: some View {
ScrollView {
Text("""
Here you can find activities to practise your reading skills. Reading will help you to improve your understanding of the language and build your vocabulary.
The self-study lessons in this section are written and organised according to the levels of the Common European Framework of Reference for languages (CEFR). There are different types of texts and interactive exercises that practise the reading skills you need to do well in your studies, to get ahead at work and to communicate in English in your free time.
"""
)
}
.focusable(true)
.digitalCrownRotation($scrollAmount)
.onChange(of: scrollAmount) { value in
self.up = (value > prevScrollAmount)
self.prevScrollAmount = value
if up {
print("up")
} else {
print("down")
}
}
}
}
发布于 2020-11-14 19:47:34
要找到滚动方向,您将需要跟踪上一个滚动量,并在scrollAmount
更改时使用当前数量检查它。下面是一个完整的小例子:
struct ContentView: View {
@State private var up = false
@State private var scrollAmount = 0.0
@State private var prevScrollAmount = 0.0
var body: some View {
Text(up ? "Up" : "Down")
.focusable(true)
.digitalCrownRotation($scrollAmount)
.onChange(of: scrollAmount) { value in
self.up = (value > prevScrollAmount)
self.prevScrollAmount = value
}
}
}
有关更多信息,请阅读本文:如何使用watchOS ()读取watchOS上的数字冠。
滚动视图中的
皇冠一次只能控制一个视图,我认为这意味着您不能直接控制scrollView并使用.digitalCrownRotation
读取值。解决此限制的一种方法是使用.digitalCrownRotation
读取值,然后直接设置scrollView的.content.offset
。
这个解决方案的问题是,它包含了几个幻数的框架高度和滚动的最小和最大值。选择这些内容是为了使所有文本都显示出来。我知道这不是一个完美的解决方案,但我把它放在这里,希望它能给你提供一些可供借鉴的东西。
在本例中,滚动视图向上滚动时背景色为绿色,向下滚动时为红色。
struct ContentView: View {
@State private var up = false
@State private var scrollAmount = -190.0
@State private var prevScrollAmount = -190.0
var body: some View {
ScrollView {
Text("""
Here you can find activities to practise your reading skills. Reading will help you to improve your understanding of the language and build your vocabulary.
The self-study lessons in this section are written and organised according to the levels of the Common European Framework of Reference for languages (CEFR). There are different types of texts and interactive exercises that practise the reading skills you need to do well in your studies, to get ahead at work and to communicate in English in your free time.
"""
)
.frame(height: 530)
.focusable(true)
.digitalCrownRotation($scrollAmount, from: -190, through: 190)
.onChange(of: scrollAmount) { value in
self.up = (value > prevScrollAmount)
self.prevScrollAmount = value
if up {
print("up")
} else {
print("down")
}
}
}
.content.offset(x: 0, y: -CGFloat(scrollAmount))
.background(up ? Color.green : .red)
}
}
https://stackoverflow.com/questions/64836457
复制相似问题