How to scale text to fit parent view with SwiftUI?

前端 未结 6 861
-上瘾入骨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:04

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

提交回复
热议问题