swiftswiftui

How to scale text to fit parent view with SwiftUI?


I'd like to create a text view inside a circle view. The font size should be automatically set to fit the size of the circle. How can this be done in SwiftUI? I tried scaledToFill and scaledToFit modifiers, but they have no effect on the Text view:

struct ContentView : View {
    var body: some View {
        ZStack {
            Circle().strokeBorder(Color.red, lineWidth: 30)
            Text("Text").scaledToFill()
        }
    }
}

Solution

  • One can use GeometryReader in order to make it also work in landscape mode.

    It first checks if the width or the height is smaller and then adjusts the font size according to the smaller of these.

    GeometryReader{g in
        ZStack {
            Circle().strokeBorder(Color.red, lineWidth: 30)
            Text("Text")
                .font(.system(size: g.size.height > g.size.width ? g.size.width * 0.4: g.size.height * 0.4))
        }
    }
    

    enter image description here enter image description here