SwiftUI动画之几何匹配
记录一下 日常开发中经常使用到的滑块功能 如何同工几何匹配快速制作点击动画
import SwiftUIstruct MatchedGeometryEffestExamle: View {let categories = ["Home", "Popular", "Saved"]@State var selecedTitle = "Home"/// 使用@Namespace 来声明对应命名空间,给系统使用@Namespace private var namespacevar body: some View {HStack {ForEach(categories, id: \.self) { title inVStack(content: {Text(title).font(.headline).frame(maxWidth: .infinity).frame(height: 35).onTapGesture {withTransaction(Transaction.init(animation: .easeInOut)) {selecedTitle = title}}.foregroundColor(selecedTitle == title ? .red : .black)if selecedTitle == title {RoundedRectangle(cornerRadius: 10).fill(.red)/// 通过匹配id 和 namespace 系统做动画的时候就可以知道这是同一个对象,然后就自动给先后出现的为宜添加对应的效果.matchedGeometryEffect(id: "MatchedGeometryEffestExamle_RoundedRectangle", in: namespace).frame(width: 35, height: 2)}})}}.padding()}
}#Preview {MatchedGeometryEffestExamle()
}
效果如下: