nonocast / me

记录和分享技术的博客
http://nonocast.cn
MIT License
20 stars 0 forks source link

学习 MacOS 开发 (Part 11: minimal SwiftUI with swiftc) #248

Open nonocast opened 2 years ago

nonocast commented 2 years ago

app.swift

import SwiftUI

struct MyApp: App {
    var body: some Scene {
        WindowGroup {
          Text("Hello, world!")
            .frame(width: 300, height: 300)
        }
    }
}

MyApp.main()

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个解决办法:

App 结构

App essentials in SwiftUI - WWDC20 - Videos - Apple Developer

@main
struct NewAllApp: App {
    var body: some Scene {
        WindowGroup {
            Text("Hello world")
        }
    }
}

Scene

State

继续看视频: Data Essentials in SwiftUI - WWDC20 - Videos - Apple Developer

感觉就是cp了WPF的依赖属性, biubiubiu.

结论: 苹果就一定要多看视频,不管是WWDC还是Xcode的操作。

参考:

参考文档