Reputation: 8841
I have a Text that I want to decrease the font size when it appears, from a .largeTitle to .headline
Here is what I am trying so far (which doesn't work):
struct MyView: View {
@State private var fontSize: CGFloat = 100
var body: some View {
GeometryReader { geometry in
Text("Big Text - Small Text")
.font(.system(size: self.fontSize))
.onAppear {
withAnimation(Animation.linear(duration: 10)) {
// what do I do here?
}
}
}
}
}
Upvotes: 2
Views: 867
Reputation: 257493
Font size is not animatable by default. The below solution is based on custom animatable modifier.
Tested with Xcode 12 / iOS 14
struct AnimatingFontSize: AnimatableModifier {
var fontSize: CGFloat
var animatableData: CGFloat {
get { fontSize }
set { fontSize = newValue }
}
func body(content: Self.Content) -> some View {
content
.font(.system(size: self.fontSize))
}
}
struct DemoFontView: View {
@State private var smallFont = false
var body: some View {
Text("Big Text - Small Text")
.frame(maxWidth: .infinity)
.modifier(AnimatingFontSize(fontSize: smallFont ? 11 : 100))
.animation(Animation.linear(duration: 10), value: smallFont)
.onAppear {
smallFont = true
}
}
}
Upvotes: 4