Swift UI Basics 2
SwiftUI Basics 2
Button View
A Button is a view that performs an action when tapped. You can create a button using the Button view.
A ver simple button looks like this:
1 | Button("Tap me") { |
You can also customize the button’s appearance using modifiers:
1 | Button(action: { |
Use button to change the state of a view:
1 | struct ContentView: View { |
here @State is a property wrapper that allows you to create a mutable state in a view. When the state changes, the view will be re-rendered to reflect the new state.
@Binding
@Binding is a property wrapper that allows you to create a two-way connection between a view and its parent view. It is used to pass a mutable state from a parent view to a child view.
1 | struct ParentView: View { |
1 | struct ChildView: View { |
here, the isOn state in the ParentView is passed to the ChildView using the $ prefix. $ creates a binding to the isOn state in the ParentView. The ChildView can then modify the isOn state, and the changes will be reflected in the ParentView.
List View
A List is a view that displays a scrollable list of data. You can create a list using the List view.
1 | struct ContentView: View { |
Here, the List view takes an array of items and a closure that defines how to display each item. The id: \.self parameter is used to identify each item in the list.
Alert View
An Alert is a view that displays a modal dialog to the user. You can create an alert using the alert modifier.
1 | struct ContentView: View { |
Here, the alert modifier is used to display an alert when the showAlert state is true. The alert has a title, a message, and a button to dismiss the alert.
TabView
A TabView is a view that displays multiple child views in a tabbed interface. You can create a TabView using the TabView view.
1 | struct ContentView: View { |
Here, the TabView contains two child views: a Home view and a Settings view. Each child view has a tab item with a label and a system image.
TextField View
A TextField is a view that allows the user to enter text. You can create a TextField using the TextField view.
1 | struct ContentView: View { |
Here, the TextField view takes a placeholder text and a binding to the name state. The textFieldStyle modifier is used to apply a rounded border style to the text field.