Begin with VStack that contain texts as children.
struct TestView: View {
var body: some View {
VStack(alignment: .trailing) {
Text("Hello, World!")
.background(Color.green)
Text("Cat")
.background(Color.red)
Text("School")
.background(Color.blue)
}
.padding()
}
}I want the behaviour that the children expand dynamically depend on their contents, and they all have equal width.
The final result looks like this.
I use PreferenceKey and onPreferenceChange modifier. This allows children-parent communication.
- Firstly, we have
maxWidth == nil. This means children have its own preferred width at the first render. MaxWidthEqualizer.notifywill notify the preferred width back to the parent VStack viaMaxWidthEqualizer(width:).MaxWidthEqualizer(width:)takes the max value from all the reported width. And assign to$maxWidth.- Updating
maxWidthstate, will then trigger rendering with the new value ofmaxWidth.

