Animate Text style changes in SwiftUI
With the changes to SwiftUI text modifiers in iOS 16 and macOS 13, it's really easy to animate text style changes.
For example, if we want to toggle font weight between regular and bold, we can use bold() modifier that accepts a Boolean parameter. Then we just change the value from true
to false
and vice versa, depending on the state.
To animate the change, we can add animation(_:value:) modifier. For the value
parameter, we should pass the value of the state variable that alters text font weight.
struct ContentView: View {
@State private var isBold = false
var body: some View {
VStack {
Text("Hello, world!")
.bold(isBold)
.animation(.default, value: isBold)
Button("Toggle weight") {
isBold.toggle()
}
}
}
}