Reading time: 1 min

This quick recipe shows how to make the SwiftUI Text automatically adjust its size/shrink based on its frame size.

The end result looks like this:

preview

This solution works for SwiftUI 1 (iOS 13+, macOS 10.15+).

The trick is to combine lineLimit(1) with minimumScaleFactor:

extension Text {
  func autoSize(minimumScaleFactor: CGFloat = 0.01) -> some View {
    self.lineLimit(1)
      .minimumScaleFactor(minimumScaleFactor)
  }
}

And then you can use it like this:

struct AutosizeTest: View {
  @State private var frameScale = 1.0

  var body: some View {
    VStack {
      Text("I'm autosizing!")
        .font(.system(size: 40))
        .autoSize()
        .frame(width: 200 * frameScale)

      Slider(value: $frameScale, in: 0.1...1) {
        Text("Some")
      }
    }
    .padding()
  }
}

Next Post Previous Post