NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

How to group views together

Paul Hudson    @twostraws   

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.

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5

Link copied to your pasteboard.