I am trying to have a string of text be displayed within my view with an adaptable size so that it works with all text sizes and only expands its parent view when absolutely necessary.
It seems at the moment the preference for text is to move it onto multiple lines, ignoring the minimum scale factor. When the text exceeds the bounds of the parent I want it to use the minimum scale factor and only when that exceeds the bounds of the parent should the text be split across multiple lines.
Below is an example of an attempt I made using ViewThatFits. Even though the minimum scale factor of 0.7 fits within the frame the ViewThatFits returns the multiline text instead.
struct AdaptiveText: View {
var text: String
let fontType: Font
let fontWeight: Font.Weight
var body: some View {
ViewThatFits{
//Shrinking Text
Text(text)
.lineLimit(1)
.minimumScaleFactor(0.7)
.fontWeight(fontWeight)
.font(fontType)
.multilineTextAlignment(.trailing)
//MultiLine Text
Text(text)
.lineLimit(nil)
.minimumScaleFactor(0.7)
.fontWeight(fontWeight)
.font(fontType)
.multilineTextAlignment(.trailing)
}
}
}
#Preview {
AdaptiveText(text: "Hi, this is quite a big sentence I guess", fontType: .title, fontWeight: .medium)
.border(.blue)
.background(.red)
.frame(maxWidth: .infinity, minHeight: 85)
.border(Color.red)
.padding()
.border(Color.red)
}
What is being returned from the view that fits is not the shrunk text but the multiline text
Even though it does fit within the parent
If this shrunk text didn’t fit on one line like this
Thats when I’d like it to automatically be on as many lines as necessary, always attempting to shrink the text before moving to a new line.
Googling this doesn’t provide much help, everything I have tried involving .fixedSize, .lineLimit, .minimumScaleFactor doesn’t seem to work as I expect it to. Perhaps there is a method I am missing?
If anyone can help it would be greatly appreciated! Thank you!