27. Juli 2019

SwiftUI Kurzreferenz

View (entspricht UIView)

struct HelloWorldView: View {

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

}

Texte (entspricht UILabel)

Text("Hello!")

Schriftgrößen:

Text("Hello!")
    .font(.headline)

Text("Hello!")
    .font(.system(size: 100, weight: .bold))

Listen (entspricht UITableView / UITableViewController)

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

Daten aus einem Swift-Array anzeigen - dazu muss der Datentyp das Identifiable-Protokoll erfüllen (oder alternativ via List(persons, id: \.id) eine Eigenschaft zur Identifizierung angegeben werden):

struct Person : Identifiable {
    var id : Int
    var name : String
}

struct ContentView: View {
    
    let persons = [Person(id: 1, name: "Alice"), Person(id: 2, name: "Bob")]
    
    var body: some View {
        List(persons) { (person) in
    Text(person.name)
}
    }
}

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")

}

SwiftUI-View in UIViewController einbetten

let controller = UIHostingController(rootView: HelloWorldView())

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())
    }

}

UIView in SwiftUI einbetten

struct ActivityIndicator: UIViewRepresentable {

    var isAnimating: Bool = true

    func makeUIView(context: Context) -> UIActivityIndicatorView {
        return UIActivityIndicatorView()
    }

    func updateUIView(_ view: UIActivityIndicatorView, context: Context) {
        if self.isAnimating {
            view.startAnimating()
        } else {
            view.stopAnimating()
        }
    }

}