11. Juli 2019

SwiftUI Kurzreferenz

View (entspricht UIView)

struct HelloWorldView: View {

    var body: some View {
        Text("Hello!")
    }

}

Texte (entspricht UILabel)

Text("Hello!")

Listen (entspricht UITableView / UITableViewController)

List {
    Text("Item1")
    Text("Item2")
    Text("Item3")
}

Button (entspricht UIButton)

Button(
    action: {
        print("Hello!")
    },
    label: {
        Text("Button Text")
    }
)

Kurzform:

Button("Hello") {
    print("Hello world!")
}
NavigationView {
    
    NavigationLink("Go to Hello World View", destination: HelloWorldView())
        .navigationBarTitle("Title")

}

Modale Präsentation (entspricht UIViewController#present)

PresentationLink("Go to Hello World View", destination: HelloWorldView())

SwiftUI-View als UIViewController verwenden (z.B. im AppDelegate)

let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = UIHostingController(rootView: StartView())
self.window = window
window.makeKeyAndVisible()

UIViewController in SwiftUI verwenden

struct Example: UIViewControllerRepresentable {
    
    func makeUIViewController(context: Context) -> ExampleViewController {
        return ExampleViewController()
    }
    
    func updateUIViewController(_ uiViewController: ExampleViewController, context: Context) {
    }
    
}

struct ExampleView: View {

    var body: some View {
        PresentationLink("UIKit!", destination: Example())
    }

}