我有一个传统的UIImageView
,它使用CABasicAnimation
来制作动画.我将其包装在UIViewRepresentable
中,以便将其嵌入到SwiftUI视图中.它非常适用于主视图,但在使用.sheet
修改器呈现的视图中,它不会产生动画效果.我的全部代码如下(用Xcode15.3编译).
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct Microphone: UIViewRepresentable {
func updateUIView(_ uiView: UIImageView, context: Context) {
}
func makeUIView(context: Context) -> UIImageView {
let view = UIImageView(
image:
UIImage(
systemName: "mic.circle.fill",
withConfiguration: UIImage.SymbolConfiguration(pointSize: 50,weight: .bold, scale: .large)
)?
.withRenderingMode(.alwaysTemplate)
)
view.translatesAutoresizingMaskIntoConstraints = false
view.tintColor = .green
let animation = CABasicAnimation(keyPath: "transform.scale")
animation.duration = 1.3
animation.repeatCount = .greatestFiniteMagnitude
animation.autoreverses = true
animation.fromValue = 0.9
animation.toValue = 1.1
view.layer.add(animation, forKey: "scale")
return view
}
}
struct ContentView: View {
@State var showSheet = false
var body: some View {
VStack {
Microphone() // <-- animates perfectly
.frame(width: 50, height: 50)
Button("Show Sheet") { showSheet = true }
.padding(.top)
}
.sheet(isPresented: $showSheet) {
VStack {
Microphone() // <-- does not animate
.frame(width: 50, height: 50)
}
}
}
}
#Preview {
ContentView()
}
我 Select UIViewRepresentable
美元的原因是
- 该代码已经编写、测试和接受.
- 我无法制作一个原生的SwiftUI视图来流畅地制作动画,这可能是因为我的SwiftUI知识仍然相当初级.我很乐意 Select 一个解决方案,让我在纯SwiftUI中获得流畅的动画效果.