- 原文地址:SwiftUI 3D Scroll Effect
- 原文做者:Jean-Marc Boullianne
- 译文出自:掘金翻译计划
- 本文永久连接:github.com/xitu/gold-m…
- 译者:chaingangway
- 校对者:lsvih
咱们预览下今天要实现的 3D scroll 效果。学完本教程后,你就能够在你的 App 中把这种 3D 效果加入任何自定义的 SwiftUI 视图。下面咱们来开始本教程的学习。前端
首先,建立一个新的 SwiftUI 视图。为了举例说明,在这个新视图中,我会展现一个有各类颜色的矩形列表,并把新视图命名为 ColorList
。android
import SwiftUI
struct ColorList: View {
var body: some View {
Text("Hello, World!")
}
}
struct ColorList_Previews: PreviewProvider {
static var previews: some View {
ColorList()
}
}
复制代码
在视图的结构体里,添加一个用于记录颜色的变量。ios
var colors: [Color]
复制代码
在 body
变量的内部,删除掉占位 Text
。在 ScrollView
嵌套中添加一个 HStack
,以下:git
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .center, spacing: 50) {
}
}
}
复制代码
咱们使用 ForEach
在 HStack
内部根据 colors
中的数据分别建立不一样颜色的矩形。此外,我修改了矩形的 frame,让它看起来与传统 UI 布局更像一些。github
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 结构体中传入以下的颜色参数:swift
struct ColorList_Previews: PreviewProvider {
static var previews: some View {
ColorList(colors: [.blue, .green, .orange, .red, .gray, .pink, .yellow])
}
}
复制代码
你能够看到下图中的效果:后端
首先,把 Rectangle
嵌套在 GeometryReader
中。这样的话,当 Rectangle
在屏幕上移动的时候,咱们就能够得到其 frame 的引用。app
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)
}
}
}
}
}
复制代码
根据 GeometryReader
的用法要求,咱们须要修改上面定义的 HStack
的 spacing 属性。ide
在 Rectangle
中加入下面这行代码。函数
.rotation3DEffect(Angle(degrees: (Double(geometry.frame(in: .global).minX) - 210) / -20), axis: (x: 0, y: 1.0, z: 0))
复制代码
当 Rectangle
在屏幕上移动时,这个方法的 Angle
参数会发生改变。请重点看 .frame(in:)
这个函数,你能够获取 Rectangle
的 CGRect
属性 minX
变量来计算角度。
axis
参数是一个元组类型,它定义了在使用你传入的角度参数时,哪个坐标轴要发生改变。在本例中,是 Y 轴。
rotation3DEffect() 方法的文档能够在苹果官方网站的 这里 找到。
下一步,把这个案例跑起来。当矩形在屏幕上移动时,你能够看到它们在旋转。
我还修改了矩形的 cornerRadius 属性,并加上了投影效果,让它更美观。
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)
}
}
}
复制代码
若是您喜欢这篇文章,能够用这个 连接 订阅咱们的网站。若是您不是在 TrailingClosure.com 阅读本文,之后也能够来这个网站看看。
若是发现译文存在错误或其余须要改进的地方,欢迎到 掘金翻译计划 对译文进行修改并 PR,也可得到相应奖励积分。文章开头的 本文永久连接 即为本文在 GitHub 上的 MarkDown 连接。
掘金翻译计划 是一个翻译优质互联网技术文章的社区,文章来源为 掘金 上的英文分享文章。内容覆盖 Android、iOS、前端、后端、区块链、产品、设计、人工智能等领域,想要查看更多优质译文请持续关注 掘金翻译计划、官方微博、知乎专栏。