How to scale text to fit parent view with SwiftUI?

前端 未结 6 1037
-上瘾入骨i
-上瘾入骨i 2021-02-02 09:41

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 scaledToF

6条回答
  •  忘掉有多难
    2021-02-02 10:09

    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 {
            return modifier(FitSystemFont(lineLimit: lineLimit, minimumScaleFactor: minimumScaleFactor, percentage: percentage))
        }
    }
    

    So usage is like this:

    Text("Your text")
        .fitSystemFont()
    

提交回复
热议问题