How do I make two Text() views the same dynamic font size in SwiftUI, maximizing the font size?

Viewed 172

Reacting to the user’s device rotation and taking into account the various screen sizes of iPhones and iPads i want two (for example) Text() Views to have the maximum possible font size without truncating and without line wrapping. I tried a lot, lastly this and nothing worked.


struct MinimumHeightPreferenceKey: PreferenceKey {
    static var defaultValue: CGFloat = 1_000.0
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = min(value, nextValue())
    }
}

struct DetermineHeight: View{
    typealias Key = MinimumHeightPreferenceKey
    var body: some View {
        GeometryReader { proxy in
            Color.clear
                .anchorPreference(key: Key.self, value: .bounds) {
                    anchor in proxy[anchor].size.height
                }
        }
    }
}

struct ContentView: View {
    @State var minTextHeight: CGFloat = 75
    var body: some View {
        VStack {
            HStack(alignment: VerticalAlignment.firstTextBaseline){
                Text("Short Text")
                    .frame(maxHeight: minTextHeight)
                    .overlay(DetermineHeight())
                    .border(Color.red)
                    .scaledToFit()
                Text("This is a considerably longer text. ideally it should also reduce the shorter Text's size so they both look the same.")
                //.frame(minHeight: 1.0, maxHeight: minTextHeight)
                    .overlay(DetermineHeight())
                    .border(Color.green)
            }
            .font(.title)
            .lineLimit(1)
            .minimumScaleFactor(0.25)
            .onPreferenceChange(DetermineHeight.Key.self) {
                minTextHeight = $0
            }
            Text("minHeight = \(minTextHeight)")
        }
    }
}

The boxes turn out the same hight, but the texts aren’t adjusted. (Plus: if I uncomment that line I the boxes don’t resize at all. Huh?)

enter image description here

Am I trying to do the impossible?

0 Answers
Related