Best approach to modularize views into subview

Hi,

views tend to get larger and larger the more complex they become. So it’s a good idea to split them up into smaller views by creating a number of structs, one for each subview, and to use these subviews in the main view.

My question is now where to place such structs for subviews? I see two options:

  1. Place them outside the main view on the main level. This is of course the best and only solution if the subview ist used in several main views.

  2. Create a nested subview in the main view struct. If the subview is only used in the main view this seems to be somehow ‘cleaner’ to me.

Example:

struct MainView: View {
    
    var body: some View {
        VStack {
            LocalSubView()
            GlobalSubView()
        }
    }
    
    // approach with a nested  subview
    struct LocalSubView: View {
        var body: some View {
            Text("Local Subview")
        }
    }
}

// approach with a global view on the same level
// as the main view
struct GlobalSubView: View {
    var body: some View {
        Text("Local Subview")
    }
}

Any thoughts on this are welcome,
Oliver

As you say, this option should be used where the View or code is used in multiple locations. My suggestion is to place the code in a Folder in your project with a folder name of something like ReusableViews.

This option is one you might use just to make your code a little easier to read so you would extract that to a SubView within the same .swift file and name the view in a meaningful way.

Thanks for your thoughts on this.

I was not so much wondering where to place the SubView in folders or files but wether if it’s better to create a SubView struct within the MainView struct or to create the SubView struct outside the MainView struct (see my code example above). What are the pros and cons?

This, of course, makes only sense if the SubView is used nowhere else.

Personally if subview is used only in this one main view, then I tend to keep it as in your option 1

If it’s used in several places, then obviously go to option 2

Pros and cons: for the machine, I’m willing to bet it’s the same, probably no significant efficiency to gain.

For the developer: if you make it a struct that belongs to the main view (option 1) then it can only be called inside it and the auto completion won’t bother you with it elsewhere

I’d say it’s probably up to you

1 Like