tags:
- Swift
Lecture I & II - Getting Started with SwiftUI
Go take an explore, that would be fun. Xcode is Apple's IDE, offers a set of tools for iOS, macOS, watchOS, and tvOS development.
There's iPhone simulator, preview pane, navigator, inspector, run mode, select mode. Tons of features you could find on Xcode.
当你创建好一个项目,
everything is a struct
in swiftUI
class is other whole thing
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, World!")
}
.padding()
}
}
#Preview {
ContentView()
}
ContentView:view{}
functional programming
AKA protocol-oriented programming
struct ContentView: View {}
Here, :view means the struct ContentView behaves like a View
in swift you can a variable like this:
var i: Int // i is an integer
var s: String // s is a string
这其实是一样的,但是又不太一样,View又是一种你可以behave like 的东西,而且你必须按照一定范式来进行,这个范式在 Swift 中叫做协议(protocol),所以 Swift 也叫 Protocol- Oriented Programming Language
OOP 用于封装数据,POP 用于封装行为。所以你想要 ContentView,你就需要 behave like a View。而一旦 ContentView behave like a View 后,你就可以使用 View 定义的所有东西(现成的 built-in)
(View 就是屏幕上的一块长方体画布(所以也叫canvas?),涂涂画画然后taking events反馈一个view)
那什么叫 behave like a view?
View 是一种 protocol,要求你在你的 Struct 内定义 var body: some View {}
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, World!")
}
.padding()
}
var body是一个computed property,即下面的代码。意思是SwiftUI 中,var body: some View
并没有存储具体的值,而是每次访问时动态计算并返回一个视图结构。(每次访问,视图都可能变化,所以用 var
)
{
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, World!")
}
.padding()
}
what is some view?
this means that the type of this variable has to be any struct in the whole world as long as it behaves like a view.
this two is the same:
struct ContentView: View {
var body: some View {
Text("Hello there")
}
}
struct ContentView: View {
var body: Text {
Text("Hello there")
}
}
which view? some view! and this some tell swift execute this code and see what it returns and use whatever it returns
if you want behave like a view, you have to have a vairable that returns some other view
也就是说,由于 View 是 computed property,你不能确定每次运行后生成的 view body 都是一样的,所以使用 some view,是这样的么?
在 body 中,我们有 image struct 有 text struct,这些都 behave like a view,together,here we have ContentView
Image(systemName: "globe) // named parameters
VStack {}
的作用就是将 {} 中的 View 组合成一个 TupelView 然后返回结果 所以你不能这样:
struct ContentView: View {
var body: Text {
VStack(content: {
Text("Hello")
Text("World")
})
}
}
@ViewBuilder的作用就是确定这个some View 到底是什么View(TupleView)
这也是一个Function相当于
VStack(content: {
xxxxx
})
.imageScale(.large)等这些函数被称为 View modifier
views are immutable
@State
what does this mean?
why cannot use for loop inside a view?
ForEach is a view
implicit returns
var cards: some View{
return VStack{
}
}
internal parameter name and external parameter name
编写主题的逻辑的函数
trailing closure syntax只有在最后一个参数是闭包时才可以用
.opacity