Black Friday 2024 deal: 30% off our Swift and SwiftUI books! Learn more ...Black Friday 2024 deal:30% off our Swift and SwiftUI books >>
Quick Tip Icon
Quick Tip

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()
            }
        }
    }
}
Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Black Friday 2024 offer: 30% off!$35$25

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms
Black Friday 2024 offer: 30% off!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35$25