I tried your idea in my sample, but it doesn't work for me:
The problem is, that I need to check whether the two-line text fits horizontally side-by-side to other views, and if not use a completely different layout where the same text has the whole width and the other views are below.
See this sample:
struct AmountRowView: View {
let title: String
let amount: String = "$ 10.00" // could vary, doesn't matter for the problem
var body: some View {
let titleView = Text(title)
.multilineTextAlignment(.leading)
let amountView = Text(amount)
.border(.gray)
let shortLayout = HStack(alignment: .center) {
titleView.border(.green)
Spacer(minLength: 2)
amountView
} // green = short
let mediumLayout = HStack(alignment: .lastTextBaseline) {
ZStack {
// Measurer: reports the full unwrapped height at the proposed width.
// Drives the fit check; never visible.
Text(title)
.fixedSize(horizontal: false, vertical: true)
.hidden()
.accessibilityHidden(true)
// Renderer: the actual 2-line layout.
Text(title)
.lineLimit(2, reservesSpace: true)
}
.border(.red)
// .lineLimit(2, reservesSpace: true)
// .fixedSize(horizontal: false, vertical: true)
Spacer(minLength: 2)
amountView
} // red = medium
let longLayout = VStack(alignment: .leading) {
titleView.border(.blue)
HStack {
Spacer()
amountView
}
} // blue = long
ViewThatFits(in: .horizontal) {
shortLayout
mediumLayout
longLayout // <=== comment / uncomment this line, then change dynamic fontSize
}
}
}
struct ContentView: View {
var body: some View {
List {
Section {
// should fit in greenV when font <= AX2
AmountRowView(title: "Short title:")
// should fit in redV from XXlarge to AX1
AmountRowView(title: "Medium title, more text:")
// needs blueV with fontsize >= XXlarge, smaller font fits in redV
AmountRowView(title: "Long title with way more text to show here:")
} header: { Text("ViewThatFits") }
}
}
}
When you comment out longLayout (line 49), you'll see that mediumLayout fits for the middle row, but is not taken from ViewThatFits if longLayout is the 3rd option.
Topic:
SwiftUI
SubTopic:
SwiftUI Q&A