很多出彩的app,都有很好的app体验,还有一部分很重要的组成部分,那就是动画,动画会让app的过渡更平滑。从而给用户带来很好的体验。接下来我们一起来看看动画吧
在这个示例中,当点击Button时,我们会切换isAnimated的值,然后做动画。我们的大小其实已经设置了,但是当我们点击Button,你会发现视图变化非常生硬,其实我们只需要加上下面的代码就好了
withAnimation {
isAnimated.toggle()
}
只需要把切换的变量包在动画方法中间,就可以实现动画效果了。
struct AnimationSample: View {
@State var isAnimated: Bool = false
var body: some View {
VStack {
Button("Button") {
isAnimated.toggle()
}
Spacer()
RoundedRectangle(cornerRadius: isAnimated ? 50 : 25)
.fill(isAnimated ? Color.yellow : Color.mint)
.frame(
width: isAnimated ? 100 : 200,
height: isAnimated ? 100 : 200
)
}
}
}
我们在使用一些动画属性来做更丰富的动画效果
放缩过渡动画
struct AnimationSample: View {
@State private var isShowing = false
var body: some View {
VStack {
Button("Toggle") {
withAnimation(.easeInOut) {
self.isShowing.toggle()
}
}
if isShowing {
Text("Hello, World!")
.transition(.scale)
}
}
.padding()
}
}
在这个示例中,点击按钮时,文本视图将使用 .scale
过渡动画进行显示和隐藏。
位移动画
struct AnimationSample: View {
@State private var xOffset = 0.0
var body: some View {
VStack {
Button("Move Button") {
withAnimation(.easeInOut) {
xOffset += 50
}
}
Circle()
.offset(x: xOffset, y: 0)
}
}
}
在上述示例中,当我们每次点击button时,圆都会在正x轴方向移动50
旋转动画
struct AnimationSample: View {
@State private var angle = 0.0
var body: some View {
VStack {
Button("Rotate") {
withAnimation(.linear(duration: 1)) {
angle += 360
}
}
Rectangle()
.rotationEffect(.degrees(angle))
}
}
}
在上述示例中,当我们每次点击button时,矩形都会旋转360度
组合动画
你可以和任意属性组合,来写出你想要的动画效果
struct AnimationSample: View {
@State var isAnimated: Bool = false
var body: some View {
VStack {
Button("Button") {
withAnimation {
isAnimated.toggle()
}
}
Spacer()
RoundedRectangle(cornerRadius: isAnimated ? 50 : 25)
.fill(isAnimated ? Color.yellow : Color.mint)
.frame(
width: isAnimated ? 100 : 200,
height: isAnimated ? 100 : 200
)
.rotationEffect(Angle(degrees: isAnimated ? 360 : 0))
.offset(y: isAnimated ? 300 : 0)
Spacer()
}
}
}
这次加入了rotationEffect,此属性是一个旋转效果,当isAnimated是true时,视图会旋转360度。
offset是一个位移参数,可以在x,y轴来移动。当前例子是把视图往上移动300.
效果如下
withAnimation(Animation.easeOut(duration: 0.1).delay(0.1)) { self.isAnimated.toggle()
}
withAnimation方法的第一个参数是一个Animation类型,Animation有很多组合。在实际的项目中要调出合适的动画很费时间,只有知道每个动画的特性才可以更好的组合出更好的动画
以上就是要介绍的动画内容