在SwiftUI 中创建一个内容切换效果

文字内容切换效果

界面布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct ContentView: View {
@State private var text: Int = 0
var body: some View {
VStack(spacing: 20) {
Text("$\(text)")
.font(.largeTitle.bold())
.contentTransition(.numericText(value: Double(text)))
Button {
withAnimation(.bouncy) {
text = .random(in: 100...10000)
}
} label: {
Text("Update")
}

}
.padding()
}
}

效果如下:

注意contentTransition 修饰器的系统要求为: @available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *)

SF Symbol 切换效果

界面布局:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct ContentView: View {
@State private var sfImage: String = "house.fill"
@State private var sfCount: Int = 1
var body: some View {
VStack(spacing: 20) {
Image(systemName: sfImage)
.font(.largeTitle.bold())
.contentTransition(.symbolEffect(.automatic))
Button {
let images:[String] = ["suit.heart.fill", "house.fill", "gearshape", "person.circle.fill", "iphone", "macbook"]
withAnimation(.bouncy) {
sfCount += 1
sfImage = images[sfCount % images.count]
}
} label: {
Text("Update")
}

}
.padding()
}
}

效果如下:

注意

  • contentTransition 修饰器的系统要求为: @available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *);

  • symbolEffect 修饰器的系统要求为:@available(iOS 17.0, macOS 14.0, tvOS 17.0, watchOS 10.0, *)