gpt4 book ai didi

animation - SwiftUI 匹配几何 + LazyVStack = 崩溃

转载 作者:行者123 更新时间:2023-12-04 03:51:10 24 4
gpt4 key购买 nike

我花了几个小时来构建这个例子,我不确定我是否做错了什么,或者在使用 matchedGeometry + LazyVStack 时有一个错误使应用程序崩溃。
在下面的视频中,当我单击第三个矩形(应用启动时不可见)时,应用崩溃了。如果我用 LazyVStack 替换 VStack ,崩溃就会消失,但显然我想延迟加载我的东西。
Xcode 版本:版本 12.0.1 (12A7300)
enter image description here
enter image description here

struct ContentView: View {
@Namespace var namespace
@State var selected: Int?


var body: some View {
ZStack {
VStack {
Text("Cool rectangles")

if selected == nil {
ScrollView(.vertical, showsIndicators: false) {
BoxList(namespace: namespace, selected: $selected)
}
}
}

if let id = selected {
Rectangle()
.foregroundColor(.red)
.matchedGeometryEffect(id: id, in: namespace)
.onTapGesture {
withAnimation{
selected = nil
}
}

}

}
}
}

struct BoxList: View {
let namespace: Namespace.ID
@Binding var selected: Int?

var body: some View {
LazyVStack {
ForEach(0..<10){ item in
Rectangle()
.matchedGeometryEffect(id: item, in: namespace)
.frame(width: 200, height: 200)
.onTapGesture {
withAnimation {
selected = item
}
}
}
}
}
}

最佳答案

问题是你破坏了 ScrollView 破坏匹配的布局。
这是固定变体。使用 Xcode 12/iOS 14 测试
demo

struct ContentView: View {
@Namespace var namespace
@State var selected: Int?


var body: some View {
ZStack {
VStack {
Text("Cool rectangles")

ScrollView(.vertical, showsIndicators: false) {
BoxList(namespace: namespace, selected: $selected)
}.opacity(selected == nil ? 1 : 0)
} // << or place here opacity modifier here

if let id = selected {
Rectangle()
.foregroundColor(.red)
.matchedGeometryEffect(id: id, in: namespace)
.onTapGesture {
withAnimation{
selected = nil
}
}

}

}
}
}

struct BoxList: View {
let namespace: Namespace.ID
@Binding var selected: Int?

var body: some View {
LazyVStack {
ForEach(0..<10){ item in
if item == selected {
Color.clear // placeholder to avoid duplicate match id run-time warning
.frame(width: 200, height: 200)
} else {
Rectangle()
.matchedGeometryEffect(id: item, in: namespace)
.frame(width: 200, height: 200)
.onTapGesture {
withAnimation {
selected = item
}
}
}
}
}
}
}

关于animation - SwiftUI 匹配几何 + LazyVStack = 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64414041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com