Displaying Elements

  • A view that is responsible for displaying an Element hierarchy.

    A view controller that renders content via Blueprint might look something like this:

    final class HelloWorldViewController: UIViewController {
    
       private var blueprintView = BlueprintView(element: nil)
    
       override func viewDidLoad() {
           super.viewDidLoad()
    
           let rootElement = Label(text: "Hello, world!")
           blueprintView.element = rootElement
           view.addSubview(blueprintView)
        }
    
        override func viewDidLayoutSubviews() {
            super.viewDidLayoutSubviews()
            blueprintView.frame = view.bounds
        }
    
    }
    
    See more

    Declaration

    Swift

    public final class BlueprintView : UIView
  • A SwiftUI view which wraps a Blueprint element, which can be used to preview Blueprint elements via Xcode’s preview functionality (enable via the Editor > Canvas menu).

    You can leverage ElementPreview by adding something like this to the bottom of the file which contains your Blueprint element, then as you edit and work on your element, the live preview will update to show the current state of your element:

    
    struct MyElement : Element {
       ...
    }
    
    // Add this at the bottom of your element's source file.
    
    #if DEBUG && canImport(SwiftUI) && !arch(i386) && !arch(arm)
    
    import SwiftUI
    
    @available(iOS 13.0, *)
    struct MyElement_Preview: PreviewProvider {
        static var previews: some View {
            ElementPreview {
                MyElement()
            }
        }
    }
    
    #endif
    
    

    Uhhh

    You’re probably asking… Why the !arch(i386) check above? Turns out, a compiler bug! SwiftUI is only available on 64 bit devices, but the canImport check erroneously finds it when building to target iOS 10 devices. Until we drop iOS 10, this part of the check is also required.

    Details

    It’s important that you keep the PreviewProvider in the same file as the element that you are editing.

    Why? Xcode uses a new feature called “Dynamic Replacement” to re-compile the source file you are editing, and inject it back into the running app which drives the preview. This only works on the level of a single file – if your preview and element live in separate files, Xcode needs to recompile your entire module which will slow down preview updates greatly.

    You can learn more about Xcode previews here: https://nshipster.com/swiftui-previews/

    Requirements

    You must be running Xcode 11 and Catalina to take advantage of live previews. They do not work on Mojave. Your selected simulator must also be an iOS 13 device.

    See more

    Declaration

    Swift

    @available(iOS 13.0, *)
    public struct ElementPreview : View