当前位置: 首页 > 科技观察

用SwiftUI实现3D滚动效果

时间:2023-03-23 01:46:17 科技观察

今天先来预览一下要实现的3D滚动效果。完成本教程后,您可以将此3D效果添加到应用程序中的任何自定义SwiftUI视图。让我们开始本教程的学习。入门首先,创建一个新的SwiftUI视图。为了说明,在这个新视图中,我将显示一个具有各种颜色的矩形列表,并将新视图命名为ColorList。importSwiftUIstructColorList:View{varbody:someView{Text("Hello,World!")}}structColorList_Previews:PreviewProvider{staticvarpreviews:someView{ColorList()}}颜色数据在视图的结构体中,添加一个记录颜色的变量。varcolors:[Colors]在body变量中实现这个列表,删除占位符Text。在ScrollView嵌套中添加一个HStack,如下:varbody:someView{ScrollView(.horizo??ntal,showsIndicators:false){HStack(alignment:.center,spacing:50){}}}displayrectangle我们在HStack里面根据颜色使用ForEach每个中的数据创建不同颜色的矩形。此外,我修改了矩形的框架,使其看起来更像传统的UI布局。varbody:someView{ScrollView(.horizo??ntal,showsIndicators:false){HStack(alignment:.center,spacing:20){ForEach(colors,id:\.self){colorinRectangle().foregroundColor(color).frame(width:200,height:300,alignment:.center)}}}}在Preview结构中传入如下颜色参数:structColorList_Previews:PreviewProvider{staticvarpreviews:someView{ColorList(colors:[.blue,.green,.orange,.red,.gray,.pink,.yellow])}}效果如下图:添加3D效果首先在GeometryReader中嵌套Rectangle。这样,当Rectangle在屏幕上移动时,我们可以获得对其框架的引用。varbody:someView{ScrollView(.horizo??ntal,showsIndicators:false){HStack(alignment:.center,spacing:230){ForEach(colors,id:\.self){colorinGeometryReader{geometryinRectangle().foregroundColor(color).frame(width:200,height:300,alignment:.center)}}}}}根据GeometryReader的使用需求,我们需要修改上面定义的HStack的spacing属性。将以下代码行添加到Rectangle。.rotation3DEffect(Angle(degrees:(Double(geometry.frame(in:.global).minX)-210)/-20),axis:(x:0,y:1.0,z:0))当矩形是在屏幕上该方法的Angle参数在向上移动时发生变化。请重点关注.frame(in:)函数,可以得到Rectangle的CGRect属性的minX变量来计算角度。axis参数是一个元组类型,它定义了在使用你传入的角度参数时要改变哪个轴。在本例中是Y轴。rotation3DEffect()方法的文档可以在Apple的官方网站上找到。接下来,运行案例。您可以看到矩形在屏幕上移动时旋转。我还修改了矩形的cornerRadius属性并添加了阴影,使其更美观。很酷吧!最终效果structColorList:View{varcolors:[Color]varbody:someView{ScrollView(.horizo??ntal,showsIndicators:false){HStack(alignment:.center,spacing:230){ForEach(colors,id:\.self){colorinGeometryReader{geometryinRectangle().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(度数:(双(geometry.frame(in:.global).minX)-210)/-20),axis:(x:0,y:1.0,z:0))}}}.padding(.horizo??ntal,210)}}}