NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

How to group views together

Paul Hudson    @twostraws   

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

10 lines of text reading “Line 1” through “Line 10”.

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

11 lines of text reading “Line 1” through “Line 11”.

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 Stream

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.

Try now!

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

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI 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 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 Beyond Code

Was this page useful? Let us know!

Average rating: 4.6/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.