I'm trying to animate opacity on appear/disappear of Text view with a simple linear gradient.
Here's the "minimum" code I have right now:
import SwiftUI
struct ContentView: View {
@State var shown: Bool = true
var body: some View {
VStack {
ZStack {
if shown {
TextView()
}
}
.frame(height: 100)
Button("Show Toggle") {
shown.toggle()
}
}
}
}
struct TextView: View {
var body: some View {
text
.overlay(gradient)
.mask(text)
.transition(transition)
}
var gradient: LinearGradient {
LinearGradient(
colors: [Color.white, Color.blue],
startPoint: .leading, endPoint: .trailing
)
}
var transition: AnyTransition {
.asymmetric(
insertion: .opacity.animation(.linear(duration: 0.500)),
removal: .opacity.animation(.linear(duration: 0.500))
)
}
var text: some View {
Text("Hello World")
.fontWeight(.bold)
.font(.largeTitle)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Notice: I'm using the
view.overlay(gradient).mask(view)pattern in order for the gradient view to not be greedy.
As a result, the animation looks like this:
Notice how the view doesn't "just" fade out -- it first turns black and then fades out.
I can fix opacity issues by just doing gradient.mask(text) instead of the other pattern, but then I run into other issues with the gradient view being greedy
