用 SwiftUI 實現(xiàn) 3D Scroll 效果
我們預(yù)覽下今天要實現(xiàn)的 3D scroll 效果。學完本教程后,你就可以在你的 App 中把這種 3D 效果加入任何自定義的 SwiftUI 視圖。下面我們來開始本教程的學習。
入門
首先,創(chuàng)建一個新的 SwiftUI 視圖。為了舉例說明,在這個新視圖中,我會展示一個有各種顏色的矩形列表,并把新視圖命名為 ColorList。
- import SwiftUI
 - struct ColorList: View {
 - var body: some View {
 - Text("Hello, World!")
 - }
 - }
 - struct ColorList_Previews: PreviewProvider {
 - static var previews: some View {
 - ColorList()
 - }
 - }
 
顏色數(shù)據(jù)
在視圖的結(jié)構(gòu)體里,添加一個用于記錄顏色的變量。
- var colors: [Colors]
 
實現(xiàn)這個列表
在 body 變量的內(nèi)部,刪除掉占位 Text。在 ScrollView 嵌套中添加一個 HStack,如下:
- var body: some View {
 - ScrollView(.horizontal, showsIndicators: false) {
 - HStack(alignment: .center, spacing: 50) {
 - }
 - }
 - }
 
展示矩形
我們使用 ForEach 在 HStack 內(nèi)部根據(jù) colors 中的數(shù)據(jù)分別創(chuàng)建不同顏色的矩形。此外,我修改了矩形的 frame,讓它看起來與傳統(tǒng) UI 布局更像一些。
- var body: some View {
 - ScrollView(.horizontal, showsIndicators: false) {
 - HStack(alignment: .center, spacing: 20) {
 - ForEach(colors, id: \.self) { color in
 - Rectangle()
 - .foregroundColor(color)
 - .frame(width: 200, height: 300, alignment: .center)
 - }
 - }
 - }
 - }
 
在 Preview 結(jié)構(gòu)體中傳入如下的顏色參數(shù):
- struct ColorList_Previews: PreviewProvider {
 - static var previews: some View {
 - ColorList(colors: [.blue, .green, .orange, .red, .gray, .pink, .yellow])
 - }
 - }
 
你可以看到下圖中的效果:
增加 3D 效果
首先,把 Rectangle 嵌套在 GeometryReader 中。這樣的話,當 Rectangle 在屏幕上移動的時候,我們就可以獲得其 frame 的引用。
- var body: some View {
 - ScrollView(.horizontal, showsIndicators: false) {
 - HStack(alignment: .center, spacing: 230) {
 - ForEach(colors, id: \.self) { color in
 - GeometryReader { geometry in
 - Rectangle()
 - .foregroundColor(color)
 - .frame(width: 200, height: 300, alignment: .center)
 - }
 - }
 - }
 - }
 - }
 
根據(jù) GeometryReader 的用法要求,我們需要修改上面定義的 HStack 的 spacing 屬性。
在 Rectangle 中加入下面這行代碼。
- .rotation3DEffect(Angle(degrees: (Double(geometry.frame(in: .global).minX) - 210) / -20), axis: (x: 0, y: 1.0, z: 0))
 
當 Rectangle 在屏幕上移動時,這個方法的 Angle 參數(shù)會發(fā)生改變。請重點看 .frame(in:) 這個函數(shù),你可以獲取 Rectangle 的 CGRect 屬性 minX 變量來計算角度。
axis 參數(shù)是一個元組類型,它定義了在使用你傳入的角度參數(shù)時,哪一個坐標軸要發(fā)生改變。在本例中,是 Y 軸。
rotation3DEffect() 方法的文檔可以在蘋果官方網(wǎng)站的 這里 找到。
下一步,把這個案例跑起來。當矩形在屏幕上移動時,你可以看到它們在旋轉(zhuǎn)。
我還修改了矩形的 cornerRadius 屬性,并加上了投影效果,讓它更美觀。
Pretty cool right!
最終效果
- struct ColorList: View {
 - var colors:[Color]
 - var body: some View {
 - ScrollView(.horizontal, showsIndicators: false) {
 - HStack(alignment: .center, spacing: 230) {
 - ForEach(colors, id: \.self) { color in
 - GeometryReader { geometry in
 - Rectangle()
 - .foregroundColor(color)
 - .frame(width: 200, height: 300, alignment: .center)
 - .cornerRadius(16)
 - .shadow(color: Color.black.opacity(0.2), radius: 20, x: 0, y: 0)
 - .rotation3DEffect(Angle(degrees: (Double(geometry.frame(in: .global).minX) - 210) / -20), axis: (x: 0, y: 1.0, z: 0))
 - }
 - }
 - }.padding(.horizontal, 210)
 - }
 - }
 - }
 

















 
 
 




 
 
 
 