53

A demo implementation of SwiftUI for the Web

 4 years ago
source link: https://www.tuicool.com/articles/mam6bii
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

SwiftWebUI

More details can be found on the related blog post at the Always Right Institute .

At WWDC 2019 Apple announced SwiftUI . A single "cross platform", "declarative" framework used to build tvOS, macOS, watchOS and iOS UIs. SwiftWebUI is bringing that to the Web :heavy_check_mark:

Disclaimer: This is a toy project! Do not use for production. Use it to learn more about SwiftUI and its inner workings.

SwiftWebUI

So what exactly is SwiftWebUI? It allows you to write SwiftUI Views which display in a web browser:

import SwiftWebUI

struct MainPage: View {
  @State var counter = 0
  
  func countUp() { 
    counter += 1 
  }
  
  var body: some View {
    VStack {
      Text("  :bread: #\(counter)")
        .padding(.all)
        .background(.green, cornerRadius: 12)
        .foregroundColor(.white)
        .tapAction(self.countUp)
    }
  }
}

Results in:

JfIf6br.gif

Unlike some other efforts this doesn't just render SwiftUI Views as HTML. It also sets up a connection between the browser and the code hosted in the Swift server, allowing for interaction - buttons, pickers, steppers, lists, navigation, you get it all!

In other words: SwiftWebUI is an implementation of (many but not all parts of) the SwiftUI API for the browser.

To repeat the Disclaimer : This is a toy project! Do not use for production. Use it to learn more about SwiftUI and its inner workings.

Requirements

As of today SwiftWebUI requires a macOS Catalina installation to run. An installation of Xcode 11 is required to get the new Swift 5.1 features SwiftUI makes heavy use of.

SwiftWebUI Hello World

To setup a SwiftWebUI project, create a "macOS tool project" in Xcode 11, then use the new SwiftPM integration and add https://github.com/SwiftWebUI/SwiftWebUI as a dependency.

Open the main.swift file and replace it's content with:

import SwiftWebUI

SwiftWebUI.serve(Text("Holy Cow!"))

Compile and run the app in Xcode, open Safari and hit http://localhost:1337/ :

uyAfIvE.png!web

:bread: AvocadoToast

A small SwiftWebUI sample based on the SwiftUI Essentials "Avocado Toast App". Find it over here: AvocadoToast .

jYv63my.gif

Who

Brought to you by The Always Right Institute and ZeeZide . We like feedback , GitHub stars, cool contract work , presumably any form of praise you can think of.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK