Swift Bootcamp
Swift Bootcamp
Swift Bootcamp
--------------------
1~ Ways to format layouts
2~ Inits
3~ Enums
4~ ForEach
5~ ScrollView
6~ LazyVgrid, LazyHGrid, GridItems
7~ Safe Areas
8~ Buttons
9~ @State property wrapper
10~ Extracting Functions & Views
11~ Extract Subviews
12~ @Binding property wrapper
13~ Conditionals
14~ Ternary Operators
15~ Animations
16~ Transitions
17~ Sheets (
18~ Lists and Foreach Statements
19~ NavigationStack
20~ Alerts
21~ confirmationDialogue
22~ Adding commas to number
23~ ContextMenu
------------------------------------------------------------------------
2~ Inits
----------------------------------------------
Basically an initial function that runs as soon as view is created.
Can tie things together within init so that you don't have to pass every
parameter
each time you initialize
CODE:
import SwiftUI
becomes
import SwiftUI
3~ Enums
-----------------------------------------------
CODE:
import SwiftUI
enum myAlerts {
case success
case error
}
//after body
func getAlert() -> Alert {
switch alertType {
case .error:
return Alert(title: Text(“There was an error!”))
case .success:
return Alert(title: Text(“Success!”), message: nil,
dismissButton:
.default(Text(“OK”), action: {
backgroundColor = .green
}))
default:
return Alert(title: Text(“Error”))
}
}
** can add as many cases as there are enums, in your code you will
call the getAlert function (which replaces the Alert() part of the .alert
function. You will control which mmessage pops up by setting the
alertType (part of your function) with:
alertType = .success or alertType = .error
In the example from teh vbideo, he had two buttons embedded in a
Vstack, the content of the buttons set which enum you want
(alertType) and toggled the showAlert boolean (which brings up the
actual popup). then after the vstack you call the .alert function which
contains your cleaned code function getAlert() which contains the
Alert() portion.
REMEMBER
@State var alertType: myAlerts? = nil
CODE:
OR
CODE:
}
}
}
CODE:
LazyvGrid(
columns: columns,
alignment: center,
spacing:
pinnedViews: [.sectionHeaders ]
content: {
Section (header:
Text("Section 1")
• foregroundColor (.white)
•font (.title) •frame (maxWidth: •infinity, alignment:
•leading)
.background (Color.blue)
•padding ()
){
7~ Safe Areas
------------------------------------------------------------------------
Color.black
.edgesIgnoringSafeArea(.all)
8~ Buttons
------------------------------------------------------------------------
or can take an action and a label, seems to better if you really wanna
customize the button with shapes and capsules
// content
VStack(spacing: 20) {
Text (myTitle)
.font (.title)
Text ("Count: 1")
.font (.headline)
.underline()
HStack(spacing: 20) {
Button ("BUTTON 1') {
backgroundColor = .red
myTitle = "BUTTON 1 was pressed"
}
Button ("BUTTON 2') {
backgroundColor = .purple
myTitle = "BUTTON 2 was pressed"
}
Basically wherever you can separate out code to make it look cleaner,
do that.
For example if there is some complex set of actions that happens when
a button is pressed, you can put those actions in a function and then
just call that function in the call of the button.
Also... you can seoarate out background and content in the body
For example you can create an Hstack in the content layer that
refernces the new struct which has info for a square with a certain
backgroiund color, count, and string, and you can cleanly reference
that struct 3 time sto create a horizontal array of 3 squares
Lets say you have a main view with a state variable background color
that might change
Then you have a subview but wnana change color of parent view
do that by declaring variable with binding variable
CODE:
13~ Conditionals
------------------------------------------------------------------------
CODE:
import SwiftUI
}
}
}
examples:
.frame (
width: isStartingState ? 200 : 50,
height: isStartingState ? 400 : 50)
Text (isStartingState ? "STARTING STATE!!! " : "ENDING STATE.")
if showCircle == true {
Circle()
.frame(width:100, height:100)
} else {
Rectangle()
.frame(width:100, height:100)
}
becomes
showCircle ?
AnyView(Circle().frame(width: 100, height: 100))
: AnyView(Rectangle().frame(width: 100, height: 100))
15~ Animations
------------------------------------------------------------------------
Sure, here are two versions of the code that you asked for, one using
`withAnimation` and one using the `.animation` modifier:
Using `withAnimation`:
```swift
//Creates a rectangle that spins and moves when touched
Rectangle()
.fill(Color.blue)
.frame(width: 50, height: 50)
.rotationEffect(.degrees(isRotated ? 360 : 0))
.offset(
CGSize(
width: isAnimated ? Int.random(in: -
100...100) : 0,
height: isAnimated ? Int.random(in: -
100...100) : 0
)
)
Spacer()
Button("Rotate") {
withAnimation {
isRotated.toggle()
}
}
}
}
}
```
//Creates Two rectangles that spin and move independently when
touched
VStack {
Spacer()
Rectangle()
.fill(Color.yellow)
.frame(width: 50, height: 50)
.rotationEffect(.degrees(isAnimated1 ? 360 : 0))
.offset(rectOffset1)
.onTapGesture {
withAnimation {
isAnimated1.toggle()
rectOffset1 = isAnimated1
? CGSize(
width: Int.random(in: -100 ... 100),
height: Int.random(in: -100 ... 100)
)
: .zero
}
}
Spacer()
Rectangle()
.fill(Color.blue)
.frame(width: 50, height: 50)
.rotationEffect(.degrees(isAnimated2 ? 360 : 0))
.offset(rectOffset2)
.onTapGesture {
withAnimation {
isAnimated2.toggle()
rectOffset2 = isAnimated2
? CGSize(
width: Int.random(in: -100 ... 100),
height: Int.random(in: -100 ... 100)
)
: .zero
}
}
Spacer()
}
}
You can customize the animation curves with the following code:
16~ Transitions
------------------------------------------------------------------------
import SwiftUI
ZStack(alignment: .bottom){
VStack {
Button(showView ? "Close Form" : "Show Form"){
withAnimation{
showView.toggle()
}
}
Spacer()
}
if showView {
withAnimation(.easeInOut){
RoundedRectangle(cornerRadius: 30)
.frame(height: UIScreen.main.bounds.height *
0.5)
}
.ignoresSafeArea(edges: .bottom)
}
}
17~ Sheets
------------------------------------------------------------------------
1. need binding sheet variable and need to bind it to the sheet and
need to present second screen
@State var showSheet: Bool = false
//dismisses sheet
@Environment(\.presentationMode) var presentationMode
Also takes a section function which adds a section. General format is:
Section(
header: Text(“Fruits”)) {
code
}
modifiers
.listStyle()
.listRowBackground(zColor.blue)
.accentColor(.purple)
19~ NavigationStack
------------------------------------------------------------------------
NavigationStack {
List {
ForEach(bgColors, id:\.self){bgCOlor in
Navigationlink {
bgColor
.frame(maxWidth: .infinity, maxHeight: .inifinity)
.edgesIgnoringSafeArea(.all)
} label: {
Text(bgColor.description)
}
}
}
}
modifiers
Move
.onMove(perform: {indices, newOffset in
bgColor.move(fromOffsets: IndexSet, toOffset: Int)
})
becomes
.onMove(perform: {indices, newOffset in
bgColor.move(fromOffsets: indices, toOffset: newOffset)
})
becomes
.onMove(perform: move)
+
func move(indices: IndexSet, newOffset: int) {
bgColor.move(fromOffsets: indices, toOffset: newoffset)
}
Delete
.onDelete(peform: {indexSet in
bgColor.remove(atOffsets: IndexSet)
})
becomes
.onDelete(peform: {indexSet in
bgColor.remove(atOffsets: indexSet)
})
becomes
.onDelete(perform: delete)
+
func delete(indexSet: IndexSet) {
bgColor.remove(atOffsets: indexSet)
}
Add
**for this we are going to add a button to the navigationbar
.navigationBarItems (
leading:
EditButton(),
trailing:
Button("add", action: {
add()
})
)
func add() {
bgColors.append(.purple)
}
20~ Alerts
------------------------------------------------------------------------
.alert (isPresented: $someBan, content: {
Alert(
title: (text),
message: (Text?),
primaryButton: (Alert. Button),
secondaryButton: (Alert. Button))
})
You can also extract the Alert() part to clean up code by putting that
inside a function:
funct getAlert() -> Alert {
return Alert(
title: (text),
message: (Text?),
primaryButton: (Alert. Button),
secondaryButton: (Alert. Button))
})
21~ confirmationDialogue
------------------------------------------------------------------------
.confirmationDialog("Hello", isPresented: $ellipsisButton, actions: {
Button("Blue", role:.destructive){
backgroundColor = .blue
}
Button("Black"){
backgroundColor = .black
}
Button("Red"){
backgroundColor = .red
}
Button("Yellow"){
backgroundColor = .yellow
}
})
similar to a sheet. You .confirmation dialogue, and inside perentheses you put the title, some
boolean that toggles it, and then actions inside some brackets (this is where you put all the
buttons you want in there. You can modify the buttons, for example if you set the role to
destructive it will be red.
23~ ContextMenu
------------------------------------------------------------------------
a modifier you can add to an image or anything really that brings up a
menu when long presseed