Lemon
Lemon

Reputation: 1440

Acess Widget View from app ContentView in SwiftUI

What I want to do it display Widget Views on my app Home Screen like they do in this app:

ColorWidgets App

I've tried just calling WidgetEntryView from my app, but it doesn't work.

Upvotes: 1

Views: 1368

Answers (2)

pawello2222
pawello2222

Reputation: 54556

  1. Create separate files just for your View and Entry:
struct SimpleEntry: TimelineEntry {
    let date: Date
}
struct SimpleWidgetEntryView: View {
    var entry: SimpleProvider.Entry

    var body: some View {
        Text(entry.date, style: .time)
    }
}
  1. Set the target membership for these files to both App and Widget.

It is important that you select only these two files - make sure you don't accidentally add your @main Widget / WidgetBundle to the App target.

  1. Display the Widget View directly in the ContentView:
struct ContentView: View {
     var body: some View {
        SimpleWidgetEntryView(entry: .init(date: Date()))
    }
}

Here is a GitHub repository with different Widget examples including the Preview Widget.

Upvotes: 2

EmilioPelaez
EmilioPelaez

Reputation: 19912

I wrote a view controller to display widgets in a UIKit app. I built it to automate my screenshots but you can use it as a reference.

You can see how it looks here.

It has support for all widget sizes, and while it doesn't have the exact dimensions, I think it does a decent enough job.

Like it was already mentioned, you'll need to add some of your widget view files to your app target as well.

Upvotes: 0

Related Questions