How can I declare new struct in #Preview macro

100 views Asked by At

I'm converting XCP to #Preview macro and I was wondering if it's possible to make preview like this below.

#Preview {
    struct DemoView: View {
    // make view...
    }
    DemoView()
}

Is that possible? If so please let me know. If not, please explain..

1

There are 1 answers

0
son On

#Preview macro conforms to the PreviewRegistry protocol, which has a static property preview to locate previews at runtime. It returns DeveloperToolSupport.Preview, and can contain a View or even a ViewController from UIKit in its body parameter.

Your example code will not execute because you're missing return for the DeveloperToolSupport.Preview body. Basically, function builder will not work here. (which bypass return keyword)

#Preview {
    struct DemoView: View {
    // make view...
    }
    return DemoView()
}

#Preview {
    let viewController = MyViewController(nibName: nil, bundle: nil)
    return viewController
}