Widget UI preview in SwiftUI

Viewed 333

How can I insert the preview of a widget into the app?

Can anyone give me some advice?

1 Answers

I did a naive version of a Widget configuration preview using SwiftUI. I used a RoundedRectangle with a small 3D rotation and applied a shadow:

Widget preview example

I contained the code inside a custom View called WidgetView:

struct WidgetView<Content: View>: View {

    let content: Content

    init(@ViewBuilder content: () -> Content) {
        self.content = content()
    }

    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 24, style: .continuous)
                .fill(Color(.systemBackground))
            content
        }
        .frame(width: 162, height: 162)
        .rotation3DEffect(.degrees(10), axis: (x: 1, y: 1, z: 0))
        .shadow(color: Color(UIColor.systemGray), radius: 20, x: -5, y: 10)
    }

}

The usage is quite simple. Just add the content view you want inside the Widget view:

WidgetView {
    HealthActiveEnergyView(entry: ActiveEnergyEntry.mock())
}
.preferredColorScheme(.light)
.previewLayout(layout)
struct HealthActiveEnergyView: View {

    var entry: ActiveEnergyEntry

    var body: some View {
        VStack(alignment: .leading) {
            HStack {
                Text(NSLocalizedString("Active", comment: ""))
                    .foregroundColor(entry.configuration.accentColor)
                Spacer()
                Image(systemName: "flame.fill")
                    .font(.system(.title))
                    .foregroundColor(entry.configuration.accentColor)
            }
            Text(dateFormatter.string(from: entry.date))
                .foregroundColor(Color(.systemGray))
                .font(.caption)
            HStack(alignment: .lastTextBaseline) {
                Text("\(entry.totalOfKilocalories)")
                    .font(.system(.largeTitle, design: .rounded))
                    .bold()
                    .foregroundColor(Color(.label))
                Text("kcal")
                    .foregroundColor(Color(.systemGray))
                Spacer()
            }
            Spacer()
            Text(NSLocalizedString("AVG 7 DAYS", comment: ""))
                .foregroundColor(Color(.systemGray))
                .font(.caption)
            HStack(alignment: .lastTextBaseline) {
                Text("\(entry.avgOfKilocalories)")
                    .font(.system(.callout, design: .rounded))
                    .bold()
                    .foregroundColor(Color(.label))
                Text("kcal")
                    .foregroundColor(Color(.systemGray))
                    .font(.caption)
                Spacer()
            }
        }
        .padding()
    }

}
Related