me
me copied to clipboard
学习 MacOS 开发 (Part 11: minimal SwiftUI with swiftc)
app.swift
import SwiftUI
struct MyApp: App {
var body: some Scene {
WindowGroup {
Text("Hello, world!")
.frame(width: 300, height: 300)
}
}
}
MyApp.main()
- 同目录下直接
swiftc -o app app.swift
,然后./app
就可以运行,但因为毕竟是GUI,所以从shell run起来窗口优先级会有问题,所以通过Makefile塞进.app,然后借用finder open app。
Makefile
APP=hello
SRC=src/*.swift
BIN=build/
package: build
mkdir -p $(BIN)$(APP).app/Contents/MacOS/
cp $(BIN)$(APP) $(BIN)/$(APP).app/Contents/MacOS/
run: package
open $(BIN)$(APP).app
build:
mkdir -p $(BIN)
swiftc -o $(BIN)$(APP) $(SRC)
clean:
rm -rf $(BIN)
.PHONY: clean run package build
@main
说明一下@main的情况。之前说过main.swift作为系统入口的模块,可以直接在方法以外直接写,比如
print("hello world")
从framework的角度,设计者肯定不希望用户去调用启动代码,所以就有@main
// In a framework:
public protocol ApplicationRoot {
// ...
}
extension ApplicationRoot {
public static func main() {
// ...
}
}
// In MyProgram.swift:
@main
struct MyProgram: ApplicationRoot {
// ...
}
等同于
// In a framework:
public protocol ApplicationRoot {
// ...
}
extension ApplicationRoot {
public static func main() {
// ...
}
}
// In MyProgram.swift:
struct MyProgram: ApplicationRoot {
// ...
}
// In 'main.swift':
MyProgram.main()
但这里唯一有一个bug, 就是如果只有一个文件的时候swiftc会报错
@main
class App {
static func main() {
print("hello world")
}
}
2个解决办法:
- 随便增加一个whatever.swift一起swiftc就不会报错
- 或者去掉@main,改为App.main()
App 结构
App essentials in SwiftUI - WWDC20 - Videos - Apple Developer
@main
struct NewAllApp: App {
var body: some Scene {
WindowGroup {
Text("Hello world")
}
}
}
Scene
- App: 多个Scene的集合
- Scene: 首先WindowGroup是一个Scene,它支持多窗口,比如浏览器打开多个页面,每个页面都是一个Scene, 一个WindowGroup下的View是一致的,但可以有不同的state,除了WindowGroup,还有DocumentGroup,在macOS下可以针对Preferences场景的Settings Scene
- View
State
继续看视频: Data Essentials in SwiftUI - WWDC20 - Videos - Apple Developer
- ObservableObject
- State and Binding
- @StateObject, @ObservedObject, @EnvironmentObject
感觉就是cp了WPF的依赖属性, biubiubiu.
结论: 苹果就一定要多看视频,不管是WWDC还是Xcode的操作。
参考:
- swift-evolution/0281-main-attribute.md at master · apple/swift-evolution
- What does @main do in Swift 5.3?