🗓 Sep 4, 2021⏳ 1 minutes

How to expose SwiftUI Views from internal framework

expose


👇 tl’dr at the bottom👇

When you work on a project that grows, at some point in time you might consider to structure your code into internal frameworks grouping reusable components. We can easily imagine one of the projects, containing SwiftUI Views.

Moving component to other framework means that we change accessibility rules and we need to expose components to become at least public to outside world. This is kinda natural, but becomes little bit tricky with SwiftUI.

Let’s imagine simple swiftUI view:

struct PlayView: View {
    
    var body: some View {
        VStack {
            HStack {
                Image(systemName: "play.circle")
                Text("Play")
            }
            .padding(10)
            .foregroundColor(.accentColor)
            .border(Color.accentColor, width: 1)
            Text("Be careful when pressing")
                .font(.caption2)
        }
    }
}

After moving to framework we naturally add public to struct declaration and to body computed property. However, although it’s natural for SwiftUI views to be built from single computed body property, it’s not enough this time. What actually is also needed is to include and expose initializer method like this:

public init() {}

Once this is done, our SwiftUI component can be used in our application.

👉 tl’dr

Don’t forget to add public init() {}

Tagged with: