DEV Community

BC
BC

Posted on

Learn SwiftUI (Day 16/100)

Basic Structure

struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
        }
        .padding()
    }
}
Enter fullscreen mode Exit fullscreen mode

Form

    NavigationStack {
        Form {
            Section {
                Text("Hello World")
            }
            Section {
                Text("Hello SwiftUI")
            }
        }
        .navigationTitle("Settings")
        .navigationBarTitleDisplayMode(.inline)
    }
Enter fullscreen mode Exit fullscreen mode

Change state

    @State private var clicked = 0
    var body: some View {
        Button("You have clicked \(clicked) times") {
            self.clicked += 1
        }
    }
Enter fullscreen mode Exit fullscreen mode

2-way binding

Notice the $name here:

    @State private var name = ""
    var body: some View {
        Form {
            TextField("Your name:", text: $name)
            Text(name.count != 0 ? "Hello, \(name)": "")
        }
    }
Enter fullscreen mode Exit fullscreen mode

Create view in a loop

    var body: some View {
        Form {
            ForEach(0..<50) {
                Text("Hello \($0+1)")
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)