< How to create scrolling pages of content using tabViewStyle() | How to hide and show the status bar > |
Updated for Xcode 14.2
If you need several views to act as one – for example, to transition together – then you should use SwiftUI’s Group
view. This is particularly important because, for underlying technical reasons, you can only add up to 10 views to a parent view at a time.
To demonstrate this, here’s a VStack
with 10 pieces of text:
VStack {
Text("Line 1")
Text("Line 2")
Text("Line 3")
Text("Line 4")
Text("Line 5")
Text("Line 6")
Text("Line 7")
Text("Line 8")
Text("Line 9")
Text("Line 10")
}
Download this as an Xcode project
That works just fine, but if you try adding an eleventh piece of text, you’ll get an error like this one: ambiguous reference to member 'buildBlock()’.
…almost certainly followed by a lot more error text.
This is because SwiftUI’s view building system has various code designed to let us add 1 view, 2 views, 3 views, or 4, 5, 6, 7, 8, 9, and 10 views, but not for 11 and beyond – that doesn’t work.
Fortunately, we can use a group like this:
VStack {
Group {
Text("Line 1")
Text("Line 2")
Text("Line 3")
Text("Line 4")
Text("Line 5")
Text("Line 6")
}
Group {
Text("Line 7")
Text("Line 8")
Text("Line 9")
Text("Line 10")
Text("Line 11")
}
}
Download this as an Xcode project
That creates exactly the same result, except now we can go beyond the 10 view limit because the VStack
contains only two views – two groups.
SPONSORED Build a functional Twitter clone using APIs and SwiftUI with Stream's 7-part tutorial series. In just four days, learn how to create your own Twitter using Stream Chat, Algolia, 100ms, Mux, and RevenueCat.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.