SwiftUI Flashcards

1
Q

How to layout elements

A

Ways to Layout

- VStack { } - Vertical stack

- HStack { } - Horizontal stack

- ZStack { } - Back to front stack

Spacer() - Add equally divisible space to element

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to allow UI to update a variable

A

Mark variable with @State

Prefix Variable name with $ when it needs to be read/write property

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How to display an alert

A

define alert in the declarative code

.alert( [title], isPresented: $[bool variable]) {
   Button([buttonTitle], action: [funcToCall])
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does SwiftUI use for views

A

struct

Reasons

- Simpler and faster than classes
- Structs don't mutate over time - easier for SwiftUI runtime
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Show the code for a basic Swift UI screen

A
struct ContentView: View {
    var body: some View { 
        // Content goes here
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to make a color fill the screen

A

Multiple ways

ZStack {
    Color(.blue)
        .ignoresSafeArea()
    // Your content
}

OR

VStack(
    // Your content here
)
.frame((maxWidth: .infinity, maxHeight: .infinity)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to apply modifiers only under certain conditions ?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to create a custom modifier ?

A

Create a struct that conforms to the

ViewModifier
protocol
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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to use classes with SwiftUI ?

A
import Observability

mark classes with

@Observable
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to present a SwiftUI sheet view ?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to you add ability to delete rows from a SwiftUI List ?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How to store a variable in User Defaults automatically ?

A

Use ```@AppStorage(“varname”) macro on your variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to create performant scrolling lists in SwiftUI ?

A

Create a ScrollView(.vertical) that contains a LazyVStack

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

In Swift UI, how to show a screen that “drills down” for more info

A

NavigationLink inside a NavigationStack

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

In Swift UI, how to show an unrelated screen

A

add .sheet() section

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the equivalent of a CollectionView in Swift UI ?

A

LazyHGrid / LazyVGrid inside a ScrollView

17
Q

In Swift UI. how do I modify a variable across several screens ?

A

Declare the PARAMETER with @Binding
When changed in the subview, it reflects across all views

18
Q

In SwiftUI, how do you show an action sheet ?

A

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")
}
19
Q

In SwiftUI, how to show a placeholder if there is no data available

A

```ContentUnavailableView(“title text”, systemImage: “imagename”, description: Text(“instruct text”)
~~~

20
Q

How to make structs and classes sortable ?

A
  • Add Comparable protocol
  • Add compare func - example is for a User struct
    ~~~
    static func <(lhs: User, rhs: User0 -> Bool {
    lhs.lastName < rhsLastName
    }
21
Q

in SwiftUI, How do you get actual lat/long coordinates from Mapkit

A

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)”)
}
}
}```

22
Q

Convert to MVVM

A

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

23
Q

How to handle long-press in SwiftUI

A

Use

.contextMenu { }
modifier

```.contextMenu {
Button(“Red”) { backgroundColor = .red }
Button(“Green”) { backgroundCOlor = .green }
}

24
Q

How to add swipe buttons to a List ?

A

Add

.swipeActions { }
modifier to add actions to right edge

Use .swipeActions(edge: .leading) { } to add actions to left edge

25
Q

How to implement search in SwiftUI ?

A

add modifier

.searchable(text: prompt:)

Also the item powering the list needs to update itself based on the search text.

26
Q

How to get icon on right-end of a List line ?

A

If you have 3 elements in the List item, SwiftUI doesn’t know how to format them.
Wrap all 3 in an HStack, and the 3rd element will shift to the right end of List element

27
Q

How to set keyboard button title for a TextField

A

Modifier .submitLabel(.next) or .done

28
Q

How to track and set focus ?

A

Define a hashable enum with values that cover all fields
Define field to hold focused field
@FocusState var focusedField: Field?

Add .focused() modifier
.focused($focusedField, equals: .name)

29
Q

How to show a password field ?

A

secureField.init()

30
Q

How do you pass a @State variable between views ?

A

Consuming view defines it as @Bnding var. Parent view passes $var to the consuming view

31
Q

How to configure a vqrible to be read / written from UserDefaults ?

A

Declare with @AppStorage(“keyname”)

32
Q

How to programatically scroll a scrollview ?

A

Wrap ScrollView() in a ScrollViewReader() and use SVR.scrollTo() inside a delayed main thread call

33
Q

How do I update SwiftUI data on a schedule ?

A

Wrap the updatable data in a TimeLineView(.everyMinute, …)

34
Q

How to handle flexible grid items when using LazyVGrid ?

A

Use

[GridItem(.adaptive(minimum: maximum:))]

35
Q
A