SwiftUI-基础

应用入口

Main函数与App结构体的绑定,遵循App协议

Swift 复制代码
@main
struct BaseApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

兼容UIApplicationDelegate

Swift 复制代码
@main
struct BasicApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene { ... }
}

class AppDelegate : NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        // launching...
        return true
    }
}

Swift 结构体与类的构造函数

Swift 复制代码
// struct
struct BasicApp: App {
    init() { ... }
}

// class
class AppDelegate: NSObject, UIApplicationDelegate {
    override init () { ... }
}

视图预览

遵守View协议,定义View结构体

Swift 复制代码
struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .padding()
    }
}

遵守PreviewProvider协议,定义Previews结构体

Swift 复制代码
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

UI布局

Swift 复制代码
struct ContentView: View {
    var body: some View {
        VStack(alignment: .center, spacing: 30) {
            Text("文本")
                .foregroundColor(.black)
            Button {
                print("target_action")
            } label: {
                Text("按钮")
                    .foregroundColor(.blue)
            }
        }
    }
}

VStack - 纵向布局

Swift 复制代码
var body: some View {
    VStack(alignment: .leading, spacing: 10) { // 左对齐、元素间隔10px
        Text("Column 1")
        Text("Column 2")
    }
    .padding(20) // 内边距20px
}

HStack - 横向布局

Swift 复制代码
var body: some View {
    HStack(spacing: 10) { // 居中、元素间隔10px
        Text("Column 1")
        Text("Column 2")
    }
    .padding() // 内边距-默认值
}

Text - 文本

Swift 复制代码
var body: some View {
    Text("Hello, SwiftUI!")
        .font(.title) // 字体设置
        .foregroundColor(.blue) // 文本颜色设置
        .multilineTextAlignment(.center) // 多行文本对齐方式设置
        .lineLimit(1) // 文本行数限制设置
}

Button - 按钮

Swift 复制代码
var body: some View {
    Button { 
        print("Button tapped") // 按钮点击事件处理
    } label: {
        Text("Click Me") // 按钮显示的文本
            .font(.title) // 字体设置
            .padding() // 内边距设置
            .background(Color.blue) // 背景颜色设置
            .foregroundColor(.white) // 前景颜色设置
            .cornerRadius(10) // 圆角设置
    }
}

Image - 图像

Swift 复制代码
var body: some View {
    Image("exampleImage") // 根据名称加载图像
        .resizable() // 图像可调整大小
        .frame(width: 100, height: 100) // 设置图像框的尺寸
        .background(.gray)
}

TextField - 文本输入

Swift 复制代码
@State private var textInput: String = ""
        
var body: some View {
    VStack {
        TextField("Enter text", text: $textInput)
            .textFieldStyle(RoundedBorderTextFieldStyle()) // 输入框样式设置
            .padding() // 内边距设置
        Text("You entered: \(textInput)")
    }
    .padding()
}

ScrollView - 滚动视图

Swift 复制代码
var body: some View {
    ScrollView {
        ForEach(1...10, id: \.self) { index in
            Text("Item \(index)")
                .padding()
        }
    }
}

List - 表视图

Swift 复制代码
var body: some View {
    List {
        Text("Row 1")
        Text("Row 2")
        Text("Row 3")
    }
    .listStyle(InsetListStyle()) // 样式设置
}

TextView - 多行文本输入

Swift 复制代码
@State private var textInput: String = ""
    
var body: some View {
    VStack {
        TextEditor(text: $textInput) // 多行文本输入视图
            .frame(height: 200) // 设置高度
            .border(Color.gray, width: 1) // 边框设置
        Text("You entered: \(textInput)")
    }
    .padding()
}

Alert - 警告弹窗

Swift 复制代码
@State private var showAlert = false
    
var body: some View {
    Button {
        showAlert = true
    } label: {
        Text("Show Alert")
    }
    .alert(isPresented: $showAlert) {
        Alert(title: Text("Warning"), message: Text("This is an alert!"), dismissButton: .default(Text("OK")))
    }
}

ActionSheet - 底部弹窗

Swift 复制代码
@State private var showActionSheet = false
        
var body: some View {
    Button {
        showActionSheet = true
    } label: {
        Text("Show ActionSheet")
    }
    .actionSheet(isPresented: $showActionSheet) {
        ActionSheet(title: Text("Options"), message: Text("Choose an action"), buttons: [
            .default(Text("Option 1"), action: {
                // Option 1 action
            }),
            .default(Text("Option 2"), action: {
                // Option 2 action
            }),
            .cancel() // 取消按钮
        ])
    }
}

Picker - 选择器

Swift 复制代码
@State private var selectedOption = 0
let options = ["Option 1", "Option 2", "Option 3"]
        
var body: some View {
    VStack {
        Text("Selected option: \(options[selectedOption])")
        Picker("Options", selection: $selectedOption) {
            ForEach(0..<options.count, id: \.self) { index in
                Text(options[index])
            }
        }
        .pickerStyle(WheelPickerStyle()) // 选择器样式设置
    }
    .padding()
}
相关推荐
Magnetic_h9 小时前
【iOS】方法与消息底层分析
笔记·学习·macos·ios·objective-c·cocoa
MaoJiu16 小时前
Flutter与原生端的通信
flutter·ios
iReaShare17 小时前
如何将 iPhone 备份到云端:完整指南
ios
小赵小赵福星高照~18 小时前
iOS UI视图面试相关
ui·ios·面试
杂雾无尘1 天前
苹果高管揭示苹果背后秘密:苹果为何不涉足搜索引擎领域?
ios·apple
二流小码农1 天前
鸿蒙开发:一键更新,让应用无需提交应用市场即可下载安装
android·ios·harmonyos
2501_915921431 天前
没有Mac如何完成iOS 上架:iOS App 上架App Store流程
android·ios·小程序·https·uni-app·iphone·webview
大熊猫侯佩2 天前
SwiftUI 7 新 WebView:金蛇出洞,网页江湖换新天
swiftui·webview·wwdc
瓜子三百克2 天前
defer关键字
swiftui·defer
初级代码游戏2 天前
Maui劝退:用windows直接真机调试iOS,无须和Mac配对
macos·ios·配置·maui·热重载