Middle
Cos'è matchedGeometryEffect in SwiftUI?
sobes.tech AI
Risposta dell'AI
matchedGeometryEffect in SwiftUI è un modificatore che consente di animare dolcemente il cambiamento di dimensione e posizione delle viste durante il loro spostamento tra diverse gerarchie o contenitori.
Principi di base:
- Corrispondenza degli identificatori: Si indica lo stesso identificatore (
id) per le viste che si desidera animare durante la transizione. - Fonte e destinazione: Si specifica uno spazio dei nomi (
namespace) che collega queste viste. - Animazione automatica: SwiftUI calcola automaticamente gli stati intermedi e anima la transizione da uno stato all'altro.
Applicazione:
import SwiftUI
struct ContentView: View {
@Namespace private var namespace
@State private var isExpanded = false
var body: some View {
VStack {
if isExpanded {
RoundedRectangle(cornerRadius: 10)
.fill(Color.blue)
.matchedGeometryEffect(id: "box", in: namespace)
.frame(width: 200, height: 200)
.onTapGesture {
withAnimation {
isExpanded.toggle()
}
}
} else {
RoundedRectangle(cornerRadius: 5)
.fill(Color.red)
.matchedGeometryEffect(id: "box", in: namespace)
.frame(width: 50, height: 50)
.onTapGesture {
withAnimation {
isExpanded.toggle()
}
}
}
}
}
}
In questo esempio, RoundedRectangle cambia dimensione e colore passando tra gli stati isExpanded, usando matchedGeometryEffect con l'identificatore `