I have a UIViewRepresentable
view of a UITextView
. When its text changes, I'd like for the current text to fade out as the new text fades in, but can't work out the right way to achieve that. (For example purposes, I'm setting a String
to the text view. In reality I'd be using an NSAttributedString
because I need formatted text, which SwiftUI's Text
won't do.)
Some sample code:
Our TextView
:
struct TextView: UIViewRepresentable {
@Binding var text: String
func makeUIView(context: Context) -> UITextView {
let view = UITextView()
view.isEditable = false
return view
}
func updateUIView(_ uiView: UITextView, context: Context) {
uiView.text = text
}
}
And our view:
struct ContentView: View {
@State private var text = "\(Date())"
var body: some View {
VStack {
TextView(text: $text).padding()
Button(action: {
text = "\(Date())"
}, label: {
Text("Change Text")
})
}
}
}
I tried wrapping the button's action in an animation:
withAnimation(.easeInOut(duration: 2.0) {
text = "\(Date())"
}
But that doens't seem to have an effect. If it were just a Text
view, it would animate it, but it doesn't do a fade, it moves the string around.
I tried adding .transition(.opacity)
to the TextView
, but that doens't do anything, either.
Appreciate any help anyone might be able to give.