Iamnino
Iamnino

Reputation: 380

SwiftUI: Dynamically change font size based on a string length

Is there anything in SwiftUI, that allows me to measure a string length - let's say for example inside a textfield - and reduce its font size, in case the string is longer than the textfield's width?

Ok I see, my question is ambiguous... There are two questions merged in one :D Let me split them up and get to the point that really interests me.

Dynamically changing a TextFields font should not be a big deal. I did not test it yet, but I suppose that holding a @State variable and passing it to .systemfont() inside the .font() modifier should do the trick.

Now what really interests me is: how to know if my textfields text is longer than its container?

Searching the internet led me across UIKit's intrinsicContentSize. But I did not find any useful equivalent for SwiftUI, nor did I find out, if I can use it anyway in SwiftUI.

Has anyone ever done anything similar in SwiftUI? Can anybody point me in the right direction?

Thanks

Upvotes: 2

Views: 6806

Answers (1)

Mab.init
Mab.init

Reputation: 206

There is a simple answer, however, I have found that it only works sometimes.

Text("Hello World!")
.minimumScaleFactor(0.4)

This should do what you want, only scale down the text if it will not fit. It will only scale down the text the amount required to fit in the text's frame.

I have found though that on some devices, swiftUI will scale down the text to the minimum factor no matter what. This seems to depend on the app. In some of my apps, it only works in the simulator while in others it just works fine on any device.

Hope this helps.

Upvotes: 11

Related Questions