108

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()
        }
    }
}

9 Answers 9

142

One possible "hack" is to use a big font size and a small scale factor so it will shrink itself:

ZStack {
    Circle().strokeBorder(Color.red, lineWidth: 30)
                
    Text("Text")
        .padding(40)
        .font(.system(size: 500))
        .minimumScaleFactor(0.01)
     
}
9
  • 3
    Doing some more testing with that solution, I've noticed that the text doesn't scale precisely on all aspect ratios. This is because the Text view isn't square. I could solve that issue by adding a "aspectRatio" modifier to the ZStack view: .aspectRatio(1, contentMode: .fit)
    – G. Marc
    Jul 16, 2019 at 13:26
  • 23
    Since XCode 11 Beta 6, text does automatically wrap if it doesn't fit the current width. So you need to add .lineLimit(1) to the Text element to make it work again.
    – G. Marc
    Aug 21, 2019 at 5:58
  • 1
    I am using this technique, but having a bug that on device rotation the font becomes the minimum size. When I click a button that changes an EnvironmentObject the view is refreshed and the font size is larger again.
    – Ryan
    Nov 4, 2019 at 5:50
  • 1
    You have one closing brace too many }
    – Martin
    Nov 13, 2023 at 7:21
  • 1
    @Martin, edited, thanks!
    – szemian
    Nov 13, 2023 at 22:27
65

You want to allow your text to:

  • shrink up to a certain limit
  • on 1 (or several) line(s)

You choose this scale factor limit to suit your need. Typically you don't shrink beyond readable or beyond the limit that will make your design look bad

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

}

2
  • This worked for me once I added .frame(width: width) above .scaledToFill() Aug 26, 2022 at 15:57
  • 3
    Works. Note scaledToFill is not needed with iOS 16. Apr 5, 2023 at 16:08
56

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

4
  • Actually, this solution is cleaner than the "hack" I previously marked as the right answer. The only downside is, that you have to find the correct scale factor for the font size. But once you've found it, it works for all screen sizes and orientations. Thanks!
    – G. Marc
    Dec 9, 2019 at 14:13
  • 8
    What about min(g.size.height, g.size.width) * scale?
    – Rick
    May 11, 2020 at 18:45
  • This is a nice solution for fixed text. Unfortunately, it seems that Text is rendered slightly bigger on iOS 13 than on iOS 14. This means that the scale factor won't produce the same results on different OS versions and possibly cause truncation.
    – bcause
    Dec 25, 2020 at 0:40
  • 0.4 is a magic number. Magic numbers are bad. Nov 20, 2023 at 8:23
24

I had fixed size button and this worked for me to autoshrink long text.

Text("This is a long label that will be scaled to fit:")
    .lineLimit(1)
    .minimumScaleFactor(0.5)

Source: Apple

18

Here's a solution that hides the text resizing code in a custom modifier which can be applied to any View, not just a Circle, and takes a parameter specifying the fraction of the View that the text should occupy.

(I have to agree that while @szemian's solution is still not ideal, her method seems to be the best we can do with the current SwiftUI implementation because of issues inherent in the others. @simibac's answer requires fiddling to find a new magic number to replace 0.4 any time the text or its attributes--font, weight, etc.--are changed, and @giuseppe-sapienza's doesn't allow the size of the circle to be specified, only the font size of the text.)

struct FitToWidth: ViewModifier {
    var fraction: CGFloat = 1.0
    func body(content: Content) -> some View {
        GeometryReader { g in
        content
            .font(.system(size: 1000))
            .minimumScaleFactor(0.005)
            .lineLimit(1)
            .frame(width: g.size.width*self.fraction)
        }
    }
}

Using the modifier, the code becomes just this:

    var body: some View {
        Circle().strokeBorder(Color.red, lineWidth: 30)
            .aspectRatio(contentMode: .fit)
            .overlay(Text("Text")
                .modifier(FitToWidth(fraction: fraction)))
    }

Also, when a future version of Xcode offers SwiftUI improvements that obviate the .minimumScaleFactor hack, you can just update the modifier code to use it. :)

If you want to see how the fraction parameter works, here's code to let you adjust it interactively with a slider:

struct ContentView: View {

    @State var fraction: CGFloat = 0.5

    var body: some View {
        VStack {
            Spacer()
            Circle().strokeBorder(Color.red, lineWidth: 30)
                .aspectRatio(contentMode: .fit)
                .overlay(Text("Text")
                .modifier(FitToWidth(fraction: fraction)))
            Slider(value: $fraction, in:0.1...0.9, step: 0.1).padding()
            Text("Fraction: \(fraction, specifier: "%.1f")")
            Spacer()
        }
    }
}

and here's what it looks like:

Code running on iPhone X

2
  • This will also work for multi-line text to fit the height of its parent. Just remove the line limit and change the last frame to 'height: g.size.height' The initial font size can also be set to 'g.size.height' since the font point size probably shouldn't ever need to be larger than the parent's height if that's what you're trying to fit.
    – lxmmxl56
    Mar 17, 2020 at 6:42
  • What is not ideal about szemian's solution? We seem to only say what's wrong with simibac's solution using a magic number but for the first, no reason is given, it's just declared to be bad. Why? Nov 20, 2023 at 8:30
8

I did a mix of @Simibac's and @Anton's answers, only to be broken by iOS 14.0, so here's what I did to fix it. Should work on SwiftUI 1.0 as well.

struct FitSystemFont: ViewModifier {
    var lineLimit: Int
    var minimumScaleFactor: CGFloat
    var percentage: CGFloat

    func body(content: Content) -> some View {
        GeometryReader { geometry in
            content
                .font(.system(size: min(geometry.size.width, geometry.size.height) * percentage))
                .lineLimit(self.lineLimit)
                .minimumScaleFactor(self.minimumScaleFactor)
                .position(x: geometry.frame(in: .local).midX, y: geometry.frame(in: .local).midY)
        }
    }
}

As you can see I used the geometry proxy's frame(in:) method to get the local coordinate space, and then use .midX and .midY to center it properly, since proper centering is what broke for me on iOS 14.

Then I set up an extension on View:

extension View {
    func fitSystemFont(lineLimit: Int = 1, minimumScaleFactor: CGFloat = 0.01, percentage: CGFloat = 1) -> ModifiedContent<Self, FitSystemFont> {
        return modifier(FitSystemFont(lineLimit: lineLimit, minimumScaleFactor: minimumScaleFactor, percentage: percentage))
    }
}

So usage is like this:

Text("Your text")
    .fitSystemFont()
0
4

Building on @JaimeeAz answer. Added an option to specify the minimum font.

import SwiftUI

public struct FitSystemFont: ViewModifier {
    public var lineLimit: Int?
    public var fontSize: CGFloat?
    public var minimumScaleFactor: CGFloat
    public var percentage: CGFloat

    public func body(content: Content) -> some View {
        GeometryReader { geometry in
            content
                .font(.system(size: min(min(geometry.size.width, geometry.size.height) * percentage, fontSize ?? CGFloat.greatestFiniteMagnitude)))
                .lineLimit(self.lineLimit)
                .minimumScaleFactor(self.minimumScaleFactor)
                .position(x: geometry.frame(in: .local).midX, y: geometry.frame(in: .local).midY)
        }
    }
}

public extension View {
    func fitSystemFont(lineLimit: Int? = nil, fontSize: CGFloat? = nil, minimumScaleFactor: CGFloat = 0.01, percentage: CGFloat = 1) -> ModifiedContent<Self, FitSystemFont> {
        return modifier(FitSystemFont(lineLimit: lineLimit, fontSize: fontSize, minimumScaleFactor: minimumScaleFactor, percentage: percentage))
    }
}
3

I had the same problem for a Timer. Unfortunately a timer changes the text once a second, so the text was jumping around and scaling up and down all the time. My approach was to figure, what was the longest possible timer that could be displayed - in my case "-44:44:44" - and with 50pt size that would result in a 227.7pt big frame. 227 divided by 50 (point size I used before) a width of 4.5 (rounded down) per point size. Careful: with 1pt size it gave me a 5.3 point big frame - so the bigger the font the closer to the actual text size without the frame it gets.

As I was using a GeometryReader anyway I could simple set a fixed text size, using

Text("-44:44:44")
.font(.system(size: geometry.size.width / 4.5))

Works perfectly well, if there is no '-' or no hours shown I have some space to the left and right, but the text doesn't jump around.

this could be refined with different scale-factors, depending on the amount of digits shown there - so another scale factor for "-mm:ss". This would lead to a "jump" when the hours are shown or hidden - but that happens rarely for my need.

2
  • you could just use monospaced font for this, no?
    – Pacyjent
    Jan 12 at 16:08
  • It's also my current approach, but i slightly tweaked the size with a min(geometry.size.width / scaleFactor, minFontSize) so that it will not fall below a threshold, in my case.
    – valvoline
    Jan 19 at 12:49
1

To achieve this you don't need the ZStack. You can add a background to the Text:

Text("Text text text?")
    .padding()
    .background(
       Circle()
          .strokeBorder(Color.red, lineWidth: 10)
          .scaledToFill()
          .foregroundColor(Color.white)
    )

The result is this: enter image description here

1
  • 1
    Thanks, but this isn't exactly what I need. The main problem is the automatic font size to increase to fill a given container. Your example just places the circle around a given text. Any idea how to solve this?
    – G. Marc
    Jul 15, 2019 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.