< How to create scrolling pages of content using tabViewStyle() | How to hide and show the status bar > |
Updated for Xcode 12.0
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")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
}
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()'
…perhaps followed by a long list of errors like this:
SwiftUI.ViewBuilder:3:24: note: found this candidate
public static func buildBlock<C0, C1, C2, C3, C4, C5, C6, C7, C8, C9>(_ c0: C0, _ c1: C1, _ c2: C2, _ c3: C3, _ c4: C4, _ c5: C5, _ c6: C6, _ c7: C7, _ c8: C8, _ c9: C9) -> TupleView<(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9)> where C0 : View, C1 : View, C2 : View, C3 : View, C4 : View, C5 : View, C6 : View, C7 : View, C8 : View, C9 : View
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:
var body: some View {
VStack {
Group {
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
}
Group {
Text("Line")
Text("Line")
Text("Line")
Text("Line")
Text("Line")
}
}
}
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 Would you describe yourself as knowledgeable, but struggling when you have to come up with your own code? Fernando Olivares has a new book containing iOS rules you can immediately apply to your coding habits to see dramatic improvements, while also teaching applied programming fundamentals seen in refactored code from published apps.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.