Tips, Tricks and Stuff I want to remember
This is a living article. It’s not finished, and it’s written as I learn. It may be updated over time.
Don’t download Xcode from the App Store. Xcode is huge and takes a long time installing from the App Store. Instead, download it from Apple directly. This way you can see a progress bar and it’s way faster.
This is a struct (I would call it a dict in JS):
struct Person {
var firstName = ""
var lastName = ""
}
Difference between variables and properties. Difference between functions and methods.
Variables inside a Struct are called Properties
Functions inside a Struct are called Methods
SwiftUI seems far easier to create an UI than the other methods. (I am by no means an expert on this topic)
This is a view and the basic building block of building an UI with SwiftUI.
struct ContentView: View {
var body: some View {}
}
A View ist just a structure (with a body property set). This body property is then rendered.
The Body Property of a View is a computed Property, meaning it will be generated from the Code inside.
struct ContentView: View {
var body: some View {
return ZStack {
}
}
}
// the return keyword can be omitted if it's only one line of code
struct ContentView: View {
var body: some View {
ZStack {
}
}
}
Why is there a : View
in the Structure Declaration? The Data Type for the ContentView
is ContentView
not View
.
This means it follows a Protocol (in this Case View
Protocol)
some View
means then actually: Returns some data type which conforms to the View
Protocol.
Trailing Closure Shorthands. If we look at the declaration of an init function) (e.g. of a Vstack). It looks like this:
init(alignment: HorizontalAlignment = .center, spacing: CGFloat? = nil, content: () -> Content)
So why can we do this:
VStack {
}
This is a short hand for this:
VStack(content: {
})
this works for the last parameter.
View Modifiers: methods, that create a new view from an existing view e.g. .font(.title)
Modifiers have a deterministic ordering:
Text("test text")
.background(Color.green, cornerRadius: 10)
.padding(.all)
The padding will not have a green color. But in this case, it will:
Text("test text")
.padding(.all)
.background(Color.green, cornerRadius: 10)
Shamelessly stolen from an WWDC Talk
Conditions and Modifiers: Push as much conditions as possible into modifiers, this will help SwiftUI better determine default animations
if bool {
AppIcon()
.rotationEffect(.degrees(180))
} else {
AppIcon()
}
instead do:
AppIcon()
.rotationEffect(.degrees(bool ? 180 : 0))