【发布时间】:2020-01-25 22:17:36
【问题描述】:
在我的 SwiftUI 应用程序中,每次值更改时,我都需要从 ObservedObject 获取数据。我知道我们可以用 .onReceive 做到这一点?我不太了解 Apple 关于它的文档。我不知道我该怎么做。
我的代码:
import SwiftUI
import CoreLocation
struct Compass: View {
@StateObject var location = LocationManager()
@State private var angle: CGFloat = 0
var body: some View {
VStack {
Image("arrow")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 300, height: 300)
.modifier(RotationEffect(angle: -CGFloat(self.angle.degreesToRadians)))
.onReceive(location, perform: {
withAnimation(.easeInOut(duration: 1.0)) {
self.angle = self.location.heading
}
})
Text(String(self.location.heading.degreesToRadians))
.font(.system(size: 20))
.fontWeight(.light)
.padding(.top, 15)
}
}
}
struct RotationEffect: GeometryEffect {
var angle: CGFloat
var animatableData: CGFloat {
get { angle }
set { angle = newValue }
}
func effectValue(size: CGSize) -> ProjectionTransform {
return ProjectionTransform(
CGAffineTransform(translationX: -150, y: -150)
.concatenating(CGAffineTransform(rotationAngle: angle))
.concatenating(CGAffineTransform(translationX: 150, y: 150))
)
}
}
在我的 LocationManager 类中,我有一个标题 Published 变量,这是我要检查的变量。
我需要在每次航向值改变时获取数据,以便在我的箭头移动时创建动画。对于某些原因,我需要使用 CGAffineTransform。
【问题讨论】: