XCode 与 SwiftUI 入门

斯坦福 2025 CS193p https://cs193p.stanford.edu

Mac 下载 XCode

https://developer.apple.com/cn/xcode/

开发环境

XCode只装载 Mac 和 IOS 应用开发环境就好了,什么 TVOS、WatchOS、VisionOS、iPadOS 先不管。

新建iOS应用项目

新建的样例项目,里面基本三个文件

程序入口

import SwiftUI

// 有一个 main 注解
@main
struct MeetXCodeApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

ContentView.swift

// 导包
import SwiftUI

// Swift不是面向对象语言,这里不是继承View
struct ContentView: View {
// example1 变量声明有点像Golang
//    var iInt: Int
//    var iInt1: Int8
//    var iString: String
//    var iFloat: Float
//    var iDouble: Double
    
    
// example 2 VStack是纵向排布里面堆叠一些View
//    var body: some View {
//        // .leading or .trailing
//        VStack(alignment:.trailing, spacing: 100) {
//            Image(systemName: "globe")
//                .imageScale(.large)
//                .foregroundStyle(.tint)
//            Text("hello")
//            Circle()
//        }
//        .padding()
//    }
    
// example3 可以通过参数content绑定函数,函数返回View,内容放在 VStack 中
//    var body: some View {
//        // .leading or .trailing
//        VStack(alignment:.trailing, spacing: 100, content: greetings)
//            .padding()
//    }
//
//    func greetings()->Text{
//        return Text("greetings")
//    }

// example4 函数还可以返回多个 View,函数返回类型为 TupleView 和 C++ 的 tuple 差不多
//    var body: some View {
//        VStack(alignment:.trailing, spacing: 100, content: greetings).padding()
//    }
//
//    @ViewBuilder
//    func greetings()->TupleView<(Image,Text,Circle)>{
//        Image(systemName: "globe")
//        Text("hello")
//        Circle()
//    }
    
    
// example5 还能 some View
//    var body: some View {
//        VStack(alignment:.center, spacing: 10, content: greetings).padding()
//    }
//
//    @ViewBuilder
//    func greetings()->some View{
//        Image(systemName: "globe")
//        if true {
//            Circle()
//        }
//        Text("hello1")
//    }

// example6 还能像 Lambda 表达式一样
    var body: some View {
        // z轴堆叠 还有 HStack
        ZStack(alignment:.center,  content: {
            Image(systemName: "globe")
            if true {
                Circle()
            }
            Text("hello2")
        }
        ).padding()
    }
}

// 放入 Preview 与处理代码块的东西 可以在右边的 Preview 中看到
#Preview {
    ContentView()
}

在自己 iPhone 上调试

iPhone 数据线连到 Mac 上,在调试设备中可以看到自己的手机,Build 运行下 应用就会安装到手机上。

之后甚至连到同一个Wifi下,就不用数据线了。