SwiftUI Form Tutorial — How to create settings screen using Form Part-2
So in part-1, we learn how to create Settings UI using forms and sections.
In the final code, you have seen objects with @State
property wrapper.
Normally, values in structs are not allowed to modify. SwiftUI use the @State
property wrapper to modify values in struct.
Tip: If we are adding
@State
before a property then, SwiftUI can destroy and recreate our struct whenever needed.@State
should be used with simple struct types such asString
,Int
, and arrays, and generally shouldn’t be shared with other views.
To re-store the local nature of @State
properties, Apple recommends you mark them as private
, like this:
@State private var username = ""
@State private var isDarkModeEnabled: Bool = true
@State private var downloadViaWifiEnabled: Bool = false
In Part-1, we have added @State
properties named isDarkModeEnabled and downloadViaWifiEnabled and it’s binding is done with Toggle options.
Now, you want to show options for selecting language, what we need is a Picker and Data to show in picker.
SwiftUI’s
Picker
view manages to combineUIPickerView
,UISegmentedControl
, andUITableView
in one. Best part is we don’t have to care how it works. SwiftUI does a good job of adapting itself automatically to its environment.
@State private var languageIndex = 0
var languageOptions = ["English", "Arabic", "Chinese", "Danish"]
languageIndex is set to 0, so when we set picker, it will set the 0 index as selected item.
Now, we need to bind it with Language section, so we can add below code
Picker(selection: $languageIndex, label: Text("Language")) {
ForEach(0 ..< languageOptions.count) {
Text(self.languageOptions[$0])
}
}
Output will look like this:
We can change .pickerStyle() by writing single lint of code.
for segment style
.pickerStyle(SegmentedPickerStyle())
for wheel picker kind of style
.pickerStyle(WheelPickerStyle())
That’s it. You can find full source code here.
This is how easy it is to create a settings screen / simple order/ sign up in SwiftUI using Form. And it is very much easy to compare to the UIKit.