【发布时间】:2019-08-10 14:27:45
【问题描述】:
我正在玩SwiftUI 动画。我想用这种方式用动画修改它的框架来做一个更大的正方形:
struct ContentView: View {
let squareWidth = CGFloat(100)
let squareHeight = CGFloat(100)
@State private var bigger = false
var body: some View {
VStack {
Color.green
.frame(width: bigger ? self.squareWidth * 2 : self.squareWidth, height: self.squareHeight)
.animation(.default)
Button(action: {
self.bigger.toggle()
}) {
Text("Click me!")
}
}
}
}
动画从 View 的中心发生,即锚点 (0.5, 0.5)。有没有办法改变这个锚点?我发现我可以在指定anchor 的视图上使用scaleEffect:
struct ContentView: View {
let squareWidth = CGFloat(100)
let squareHeight = CGFloat(100)
@State private var bigger = false
var body: some View {
VStack {
Color.green
.frame(width: self.squareWidth, height: self.squareHeight)
.scaleEffect(x: bigger ? 2 : 1, y: 1, anchor: .leading)
.animation(.default)
Button(action: {
self.bigger.toggle()
}) {
Text("Click me!")
}
}
}
}
但看起来并不完全相同。如果我需要应用多个效果,我应该为每个效果指定锚点,而不是一次在视图上指定锚点。在UIKit 我可以写:
var myView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
myView.layer.anchorPoint = CGPoint(x: 0, y: 0.5) //that is, the .leading of SwiftUI
【问题讨论】:
-
我不知道是否有更改动画锚点的选项,但是通过添加填充可以更改动画的中心。我在
.animation(.default)之后尝试了.padding(.leading, bigger ? self.squareWidth : 0 )您的Color.green视图。如果这不能解决您的问题,请更具体地了解应用多种效果
标签: ios swift animation uikit swiftui