SwiftUI MatchedGeometryEffect过渡不流畅问题排查与解决
SwiftUI MatchedGeometryEffect 过渡淡入淡出问题解决
我实现了两个视图:一个通过HStack展示包含图片和文本的卡片列表,点击任意卡片后会切换到展示选中卡片内容的详情视图。但使用MatchedGeometryEffect做视图过渡时,出现了不流畅的淡入淡出现象。我尝试过Stack Overflow上的多种方案,比如添加.zIndex()或.transition(.scale(scale: 1)),但都没有效果。
原相关代码
struct Test: View { var body: some View { VStack { if let selectedCard = selectedCard { VStack { cardView(card: selectedCard) .onTapGesture { withAnimation() { self.selectedCard = nil } } } } else { ScrollView(.horizontal, showsIndicators: false) { HStack { ForEach(topCardsAsTemplates) { topCardAsTemplate in TopTemplatesCardView(card: topCardAsTemplate) .padding() .onTapGesture { withAnimation() { selectedCard = topCardAsTemplate } } } } } } } } @ViewBuilder func TopTemplatesCardView(card: Card) -> some View { if card.uuid != selectedCard?.uuid { VStack { Image(systemName: "person.circle") .resizable() .matchedGeometryEffect(id: card.uuid.uuidString + "image", in: namespace) .scaledToFit() .frame(width: 80) Text(card.backgroundType.rawValue) .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace, properties: .position) .foregroundColor(.black) // .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace) } .padding() .background( RoundedRectangle(cornerRadius: 20, style: .continuous) .matchedGeometryEffect(id: card.uuid.uuidString + "back", in: namespace) .frame(width: cardSize + 50, height: cardSize + 50) .background(.clear) .foregroundColor(.gray) ) } else { Color.clear.frame(width: cardSize, height: cardSize) } } @ViewBuilder func cardView(card: Card) -> some View { VStack { Image(systemName: "person.circle") .resizable() .matchedGeometryEffect(id: card.uuid.uuidString + "image", in: namespace) .scaledToFit() .frame(width: 120) Text(card.backgroundType.rawValue) // .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace) .matchedGeometryEffect(id: card.uuid.uuidString + "text", in: namespace, properties: .position) .foregroundColor(.black) } .padding() .background( RoundedRectangle(cornerRadius: 20, style: .continuous) .matchedGeometryEffect(id: card.uuid.uuidString + "back", in: namespace) .frame(width: cardSize + 200 , height: cardSize + 200) .background(.clear) .foregroundColor(.gray) ) } }
问题求助
如何让过渡更流畅,消除淡入淡出效果?求建议。
问题解决(编辑补充)
经过多次尝试,给HStack添加.frame(maxWidth: .infinity, maxHeight: .infinity)解决了该问题。修改后的HStack代码如下:
ScrollView(.horizontal, showsIndicators: false) { HStack { ForEach(topCardsAsTemplates) { topCardAsTemplate in TopTemplatesCardView(card: topCardAsTemplate) .padding() .onTapGesture { print("display card uuid: \(topCardAsTemplate.uuid.uuidString)") withAnimation(.spring()) { selectedCard = topCardAsTemplate } } } } .frame(maxWidth: .infinity, maxHeight: .infinity) }
希望能帮助到其他开发者。
内容的提问来源于stack exchange,提问作者abs8090
相关产品推荐
相关产品推荐

