Developing Applications for iOS using SwiftUI
Total Lecture: 15
current: [7-9]
Shape,ViewModifier,Constants
Constants
1 | struct CardView: View { |
Shape
Shape
是一个继承自View
的协议,RoundedRectangle,Circle,Capsule
默认情况下,Shapes
用当前foreground color
来填充,可以通过.stroke()
和.fill()
来改变
1 | func fill<S>(_ whatToFillWith: S) -> View where S: ShapeStyle |
Custom Shape
1 | func path(in rect: CGRect) -> Path { |
Animation
制作动画的一种方法是对Shape
进行动画处理。另一种是通过ViewModifiers
ViewModifier
.aspectRatio(2/3)
等同于.modifier(AspectModifier(2/3))
AspectModifier
可以是遵从ViewModifier
协议的其他东西,这里只是语法糖
Protocol
1 | protocol ViewModifier { |
调用方式aView.modifier(MyViewModifier(arguments:...))
Cardify ViewModifier
ViewModifier语法糖
Text("🐶").modifier(Cardify(isFaceUp: true))
等同于 Text("🐶").cardify(isFaceUp: true)
1 | extension View { |
Protocol
协议最大用途是代码共享(code sharing
),可以通过extension
添加默认实现方法,协议只是事物的声明,而不是实现
filter
可作用于 Array
, Range
,String
,Dictionary
1 | filter(_ isIncluded: (Element) -> Bool) -> Array<Element> |
它是Sequence
协议的extension
View
1 | protocol View { |
默认实现
1 | extension View { |
Generics + Protocols (通用协议)
1 | protocol Identifiable { |
类型ID
是”don’t care” for Identifiable
,不过必须遵从Hashable
协议
1 | protocol Identifiable { |
或者简写
1 | protocol Identifiable { |
some
可用于协议的不透明(opaquely)类型 传入传出于 func/var
不透明意思是,只知道它的协议类型,不知道具体类型
1 | func getShape(rounded: Bool) -> some Shape { |
any
let ids = [any Identifiable]()
1 | func printId(of identifiable: some Identifiable) { |
Animation
Property Observers
1 | var isFaceUp: bool { |
属性观察不能用于@State
,@Published
变量,需使用.onChange(of:){}
1 | private var taps = 0 |
Animation
动画只是展示模型随时间发生的变化,通过ViewModifier
参数反映出来,显然Shape
也可以改变。
ViewModifer
是UI
中的主要变更代理
Implicait Animation
.animation(Animation,value:)
1 | Text("🐶").opacity(card.scary ? 1 :0 ) |
Explicitly
withAnimation(Animation) { }
Transitions
only work on Views
that are inside Containers That Are Already On-Screen.
只在当前显示的容器下有效
1 | ZStack { |
Matched Geometry Effect
两个视图不在同一个容器内时
.matchedGeometryEffect(id: ID, in: Namespace)
// ID type is a “don’t care”: Hashable
@Namespace private var myNamespace
.onAppear
.onAppear{}
Shape and ViewModifier Animation
所有动画发生在Shapes
和ViewModifiers
,Transitions
和matchedGeometryEffect
是匹配(paired
)的ViewModifiers
the animation system divides the animation’s duration up into little pieces, the Shape/ViewModifier makes sure its body draws appropriately at any “piece” value
animatableData
communication with the animation system with a single var, int the Animatable
protocol
如何想要动画化的ViewModifier
或Shape
都需要实现Animatable
协议
1 | var animatableData: Type |
Type
是don‘t care
类型,需实现VectorArithmetic
协议
AnimatblePair
实现了VectorArithmetic
,包含两个VectorArithmetics
animatableData
是read-write var
setting
是动画系统告诉Shape/VM
which “piece” to draw
getting
是动画系统获取动画的开始结束点