SwiftUI 对悬停事件不是很敏感
SwiftUI not very responsive to hover events
我正在尝试实现一个包含 200 或 300 个元素的列表,并且我想在悬停事件中更改文本的颜色。但是应用程序开始显示悬停事件的延迟。检查下面的示例代码:
struct ContentView: View {
var body: some View {
VStack {
ForEach(0...1000, id:\.self) {index in
Element()
}
}
}
}
struct Element: View {
@State private var hover = false
var body: some View {
Text("Not a fast hover!")
.foregroundColor(hover ? Color.blue : Color.white)
.onHover {_ in self.hover.toggle()}
}
}
更新:
这似乎提高了响应能力。此外,如果我更改背景而不是前景色,代码也会更加灵敏。
struct Element: View {
@State private var hover = false
var body: some View {
ZStack {
Text("Not a fast hover!").foregroundColor(Color.blue)
Text("Not a fast hover!").opacity(hover ? 0 : 1).foregroundColor(Color.white)
}
.frame(width: 200)
.onHover {_ in self.hover.toggle()}
}
}
解决方案是使用 List 组件而不是 VStack。
我正在尝试实现一个包含 200 或 300 个元素的列表,并且我想在悬停事件中更改文本的颜色。但是应用程序开始显示悬停事件的延迟。检查下面的示例代码:
struct ContentView: View {
var body: some View {
VStack {
ForEach(0...1000, id:\.self) {index in
Element()
}
}
}
}
struct Element: View {
@State private var hover = false
var body: some View {
Text("Not a fast hover!")
.foregroundColor(hover ? Color.blue : Color.white)
.onHover {_ in self.hover.toggle()}
}
}
更新:
这似乎提高了响应能力。此外,如果我更改背景而不是前景色,代码也会更加灵敏。
struct Element: View {
@State private var hover = false
var body: some View {
ZStack {
Text("Not a fast hover!").foregroundColor(Color.blue)
Text("Not a fast hover!").opacity(hover ? 0 : 1).foregroundColor(Color.white)
}
.frame(width: 200)
.onHover {_ in self.hover.toggle()}
}
}
解决方案是使用 List 组件而不是 VStack。