In WWDC2019, iOS introduced a new UI framework — SwiftUI. It aims to unify the interfaces of iPhone, iPad and Mac with a new design idea so that developers can Learn Once, Use anywhere. The new framework has been available since iOS13, and iOS developers should get their hands on it as soon as possible.

Go to the official account [iOS Development Stack] to learn more SwiftUI, iOS development related content.

View

Everything in SwiftUI is View, no matter we are familiar with Button, backgroundColor, or even color. red, they are all View.

Unlike UIView in UIKit, View in SwiftUI is no longer a class but a protocol. `

public protocol View {

    /// The type of view representing the body of this view.
    ///
    /// When you create a custom view, Swift infers this type from your
    /// implementation of the required `body` property.
    associatedtype Body : View

    /// The content and behavior of the view.
    @ViewBuilder var body: Self.Body { get}}Copy the code

{% label danger@’View’ cannot be constructed because it has no accessible initializers %} Think carefully about whether you really want to use it when you encounter this problem, and maybe use another one instead.

Commonly used to View: Text/Button/Toggle/Picker/V (Z) (H) Stack/Color/Spacer/Image/Shape/Divider and their modifier, etc.

The body variable of the @ViewBuilder tag means that it is a container that can contain any number of other views.

Button(action: btnClick) {
    VStack {
        Image(systemName: "star")
        Text("Placeholder")}}Copy the code

Modifer

{% tabs modify Label text color %}

let label = UILabel()
label.text = "UIKit"
label.textColor = UIColor.red
Copy the code
Text("SwiftUI").foregroundColor(.red)
Copy the code

{% endtabs %}

ForegroundColor and textColor in SwiftUI are essentially different, it is a modifier, it returns a View.

@inlinable public func foregroundColor(_ color: Color?). -> some View
Copy the code

So when we call foregroundColor we actually create a new View, which is the example of everything View in SwiftUI.

@State and $– Binding Value

struct ContentView: View {
    @State var isOn: Bool
    
    var body: some View {
        Toggle(isOn: $isOn) {
            Text("Toggle")}}}Copy the code

This is a two-way binding

After the binding is established, we don’t need to care about whether the modification of isOn triggers the change of Toggle state or the change of isOn variable value caused by the user clicking Toggle. SwiftUI will help us complete it.

Go to the official account [iOS Development Stack] to learn more SwiftUI, iOS development related content.

This article first appeared on my personal tech blog