NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. Lear more...
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

Check out our new book!

Swift Gems

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

Swift Gems

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

  • 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
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift