I have a view that consists of multiple UI elements in a HStack:
I want 1), 2) and 5) to take up no more space than necessary i.e. I don't need to intervene.
With 3) and 4) I would like for the summary to take up as much space as it needs at the expense of the divider that follows. If that means none, or a minimal amount, of the divider can appear then so be it. However, despite my best attempts, the summary only seems to take up a certain amount of space, causing its content to run over multiple lines to ensure the divider always appears. Giving it a layoutPriority helped slightly.
I don't want to give it a minWidth because I'd like for the distribution of width to be dynamically arranged based on the content.
Here's the code:
HStack {
// MARK: Time
HStack {
VStack {
Spacer()
Text("9am")
Spacer()
}
}.padding(.horizontal, 4)
.padding(.vertical)
.background(Color.blue.opacity(0.2))
.cornerRadius(8)
VStack {
HStack {
// MARK: Icon
Image(systemName: "cloud.drizzle.fill")
.font(Font.title2)
// MARK: Summary
VStack {
HStack {
Text("Humid and overcast")
.padding(.trailing, 2)
.background(Color.white)
.layoutPriority(100)
Spacer()
}
}
// MARK: Line
VStack {
Spacer()
Divider()
Spacer()
}
// MARK: Values
VStack {
Text(String(22.66))
Text("25%")
.foregroundColor(Color.black)
.background(Color.white)
}
Spacer()
}
}
}
And this is what it looks like:
As you can the text runs over multiple lines when there's enough room for it to fit on one line, as long as the divider that followed accommodated the longer text by being shorter.
Fixed size should be helpful here. Tested with Xcode 12.1 / iOS 14.1
struct TestLongHStack: View {
var body: some View {
HStack {
// MARK: Time
HStack {
VStack {
Spacer()
Text("9am")
Spacer()
}
}.padding(.horizontal, 4)
.padding(.vertical)
.background(Color.blue.opacity(0.2))
.cornerRadius(8)
VStack {
HStack {
// MARK: Icon
Image(systemName: "cloud.drizzle.fill")
.font(Font.title2)
// MARK: Summary
VStack {
HStack {
Text("Humid and overcast").fixedSize() // << here !!
.padding(.trailing, 2)
.background(Color.white)
.layoutPriority(100)
Spacer()
}
}
// MARK: Line
VStack {
Spacer()
Divider()
Spacer()
}
// MARK: Values
VStack {
Text(String(22.66)).bold().italic()
Text("25%").font(.footnote)
.foregroundColor(Color.black)
.background(Color.white)
}
Spacer()
}
}
}.fixedSize(horizontal: false, vertical: true)
}
}