Ios 使用UIViewRepresentable在Swift中从背景状态返回后恢复动画?
在我的SwiftUI应用程序中,出于某些原因,我必须使用makeUIView函数在UIViewRepresentable中创建“sonar”视图并设置其动画。我只是有一个动画问题:当我将应用程序移动到背景并返回到它时,动画停止并且不会自动重新启动。我在网上搜索了几种解决方案,但我不确定如何在代码中解决这个问题Ios 使用UIViewRepresentable在Swift中从背景状态返回后恢复动画?,ios,swift,swiftui,Ios,Swift,Swiftui,在我的SwiftUI应用程序中,出于某些原因,我必须使用makeUIView函数在UIViewRepresentable中创建“sonar”视图并设置其动画。我只是有一个动画问题:当我将应用程序移动到背景并返回到它时,动画停止并且不会自动重新启动。我在网上搜索了几种解决方案,但我不确定如何在代码中解决这个问题 import UIKit import SwiftUI import Foundation struct SonarView: View { var width: CGFloa
import UIKit
import SwiftUI
import Foundation
struct SonarView: View {
var width: CGFloat
var height: CGFloat
struct TargetView: UIViewRepresentable {
var width: CGFloat
var height: CGFloat
func makeUIView(context: Context) -> some UIView {
// Circle
let circle = UIView()
circle.frame = CGRect.init(x: 2, y: 2, width: width, height: height)
circle.layer.cornerRadius = width / 2
circle.layer.backgroundColor = UIColor(named: "PrimaryLight")?.cgColor
circle.layer.borderWidth = 2
circle.layer.borderColor = UIColor(named: "PrimaryDark")?.cgColor
return circle
}
func updateUIView(_ uiView: UIViewType, context: Context) {
UIView.animate(withDuration: 1.75, delay: 0, options: [.repeat, .autoreverse], animations: {
uiView.subviews[0].transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}, completion: nil)
}
}
var body: some View {
TargetView(
width: self.width,
height: self.height,
)
}
}
在SwiftUI部分,我实现了sonar视图,如下所示:
...
SonarView(width: geometry.size.height, height: geometry.size.height)
.frame(width: geometry.size.height, height: geometry.size.height)
.opacity(self.targetOpacity ? 1.0 : .zero)
.onAppear {
self.isNotNavigatingAnimationDelay = true
withAnimation(Animation.easeOut(duration: 0.5).delay(0.5)) {
self.targetOpacity = true
}
}
.onDisappear {
self.targetOpacity = false
self.targetOffset = .zero
}
...
使用
cabasicanitation
func updateUIView(_ uiView: UIViewType, context: Context) {
let basicAnimation = CABasicAnimation(keyPath: "transform.scale")
basicAnimation.toValue = 1.2
basicAnimation.duration = 1.75
basicAnimation.isRemovedOnCompletion = false
basicAnimation.repeatCount = .greatestFiniteMagnitude
basicAnimation.autoreverses = true
uiView.subviews[0].layer.add(basicAnimation, forKey: "transformanimation")
}
谢谢它在makeUIView函数中工作得很好