SwiftUI Flashcards
How to layout elements
Ways to Layout
- VStack { } - Vertical stack - HStack { } - Horizontal stack - ZStack { } - Back to front stack
Spacer() - 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 property
How 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 }
Action needs to set <boolVar> = true</boolVar>
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