我正在尝试在鼠标悬停时为单个项目设置动画。我遇到的问题是,每个项目在鼠标悬停在某个项目上时都会产生动画,而不仅仅是该特定项目。这是我所拥有的:
struct ContentView : View {
@State var hovered = false
var body: some View {
VStack(spacing: 90) {
ForEach(0..<2) {_ in
HStack(spacing: 90) {
ForEach(0..<4) {_ in
Circle().fill(Color.red).frame(width: 50, height: 50)
.scaleEffect(self.hovered ? 2.0 : 1.0)
.animation(.default)
.onHover { hover in
print("Mouse hover: \(hover)")
self.hovered.toggle()
}
}
}
}
}
.frame(minWidth:300,maxWidth:.infinity,minHeight:300,maxHeight:.infinity)
}
}
Run Code Online (Sandbox Code Playgroud)

它需要在每个视图的基础上更改 onHover 视图,即。存储悬停视图的一些标识符。
这是可能的解决方案。使用 Xcode 11.4 进行测试。
struct TestOnHoverInList : View {
@State var hovered: (Int, Int) = (-1, -1)
var body: some View {
VStack(spacing: 90) {
ForEach(0..<2) {i in
HStack(spacing: 90) {
ForEach(0..<4) {j in
Circle().fill(Color.red).frame(width: 50, height: 50)
.scaleEffect(self.hovered == (i,j) ? 2.0 : 1.0)
.animation(.default)
.onHover { hover in
print("Mouse hover: \(hover)")
if hover {
self.hovered = (i, j) // << here !!
} else {
self.hovered = (-1, -1) // reset
}
}
}
}
}
}
.frame(minWidth:300,maxWidth:.infinity,minHeight:300,maxHeight:.infinity)
}
}
Run Code Online (Sandbox Code Playgroud)
当前每个项目都会有动画,因为它们都依赖于hovered查看是否Circle将鼠标悬停在上面。为了解决这个问题,我们可以让每个圆圈都有自己的hovered状态。
struct CircleView: View {
@State var hovered = false
var body: some View {
Circle().fill(Color.red).frame(width: 50, height: 50)
.scaleEffect(self.hovered ? 2.0 : 1.0)
.animation(.default)
.onHover { hover in
print("Mouse hover: \(hover)")
self.hovered.toggle()
}
}
}
Run Code Online (Sandbox Code Playgroud)
我们ForEach可以称之为新事物CircleView,每个人Circle都有自己的真理来源。
struct ContentView : View {
var body: some View {
VStack(spacing: 90) {
ForEach(0..<2) { _ in
HStack(spacing: 90) {
ForEach(0..<4) { _ in
CircleView()
}
}
}
}
.frame(minWidth:300,maxWidth:.infinity,minHeight:300,maxHeight:.infinity)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4513 次 |
| 最近记录: |