How to layout elements
Ways to Layout
- VStack { } - Vertical stack
- HStack { } - Horizontal stack
- ZStack { } - Back to front stackSpacer() - Add equally divisible space to element
How to allow UI to update a variable
Mark variable with @State
Prefix Variable name with $ when it needs to be read/write property
How to display an alert
define alert in the declarative code
.alert( [title], isPresented: $[bool variable]) {
Button([buttonTitle], action: [funcToCall])
}What does SwiftUI use for views
struct
Reasons
- Simpler and faster than classes - Structs don't mutate over time - easier for SwiftUI runtime
Show the code for a basic Swift UI screen
struct ContentView: View {
var body: some View {
// Content goes here
}
}How to make a color fill the screen
Multiple ways
ZStack {
Color(.blue)
.ignoresSafeArea()
// Your content
}OR
VStack(
// Your content here
)
.frame((maxWidth: .infinity, maxHeight: .infinity)How to apply modifiers only under certain conditions ?
Use conditional inside the modifier
Button("Hello World") {
}
.foregroundStyle(useRedText ? .red : .blue)OR less efficient if /else
if cond { //define red button } else { //define blue button } since it creates and destroys buttons rather than just modifying the propertyHow to create a custom modifier ?
Create a struct that conforms to the
ViewModifierprotocol
struct ScreenTitle: ViewModifier {
func body(content: Content) -> some View {
content
.font(.largeTitle)
.foregroundStyle(.white)
.padding()
.background(.blue)
.clipShape(.rect(cornerRadius: 10))
}
}
Text("Hello World")
.modifier(ScreenTitle())To apply them directly without using .modifier(), you need to create an extension on View
extension View {
func screenTitleStyle() -> some View {
modifier(Title())
}
}
Text("Hello world")
.screenTitleStyle()How to use classes with SwiftUI ?
import Observability
mark classes with
@Observable
How to present a SwiftUI sheet view ?
Define a @State variable set to false
define a Struct that contains the view you want to show
add a call to
.sheet(isPresented: $<boolVar>) {
// sheet content / display the view }How to you add ability to delete rows from a SwiftUI List ?
List has to be created using ForEach() and add
.onDelete(perform: removeItems) // No params
Function removeItems has 1 argument that is an IndexSet of indexes to delete
How to store a variable in User Defaults automatically ?
Use ```@AppStorage(“varname”) macro on your variable
How to create performant scrolling lists in SwiftUI ?
Create a ScrollView(.vertical) that contains a LazyVStack
In Swift UI, how to show a screen that “drills down” for more info
NavigationLink inside a NavigationStack
In Swift UI, how to show an unrelated screen
add .sheet() section
What is the equivalent of a CollectionView in Swift UI ?
LazyHGrid / LazyVGrid inside a ScrollView
In Swift UI. how do I modify a variable across several screens ?
Declare the PARAMETER with @Binding
When changed in the subview, it reflects across all views
In SwiftUI, how do you show an action sheet ?
Code works just like an alert.
.confirmationDialog("Change background", isPresented: $showingConfirmation) {
Button("Red") { bgColor = .red }
Button("Green") { bgColor = .green }
Button("Blue") { bgColor = .blue }
Button("Cancel", role: .cancel) { }
} message: {
Text("Select a new color")
}In SwiftUI, how to show a placeholder if there is no data available
```ContentUnavailableView(“title text”, systemImage: “imagename”, description: Text(“instruct text”)
~~~
How to make structs and classes sortable ?
in SwiftUI, How do you get actual lat/long coordinates from Mapkit
Wrap your Map() in a MapReader() and use mapReader to convert position from local
~~~
MapReader { proxy in
Map(initialPosition: startPosition)
.onTapGesture { position in
if let coordinate = proxy.convert(position, from: .local) {
print(“Tapped at (coordinate)”)
}
}
}```
Convert to MVVM
Create ViewModel class
Move @State variables to ViewModel
Remove @State and private from those vars
Create ViewModel variable as @State
Update SwiftUI vars to reference View Model
How to handle long-press in SwiftUI
Use
.contextMenu { } modifier```.contextMenu {
Button(“Red”) { backgroundColor = .red }
Button(“Green”) { backgroundCOlor = .green }
}
How to add swipe buttons to a List ?
Add
.swipeActions { } modifier to add actions to right edgeUse .swipeActions(edge: .leading) { } to add actions to left edge