iOS swiftUI的實用舉例

SwiftUI 是 Apple 推出的聲明式 UI 框架,以下是一些實用技巧和最佳實踐,可以幫助你更高效地開發 iOS/macOS/watchOS/tvOS 應用。

1. 布局技巧

靈活的空間占用

// 使用 Spacer 填充可用空間 
HStack {Text("Left")Spacer() // 填充中間空間 Text("Right")
}// 使用 frame 控制視圖大小 
Text("Hello").frame(maxWidth: .infinity, maxHeight: .infinity) // 填充父視圖 .background(Color.yellow)

條件顯示視圖

@State private var isShowing = false var body: some View {VStack {if isShowing {Text("Visible")} else {EmptyView()}// 或者使用更簡潔的方式 isShowing ? Text("Visible") : nil }
}

2. 狀態管理

使用 @State 和 @Binding

struct ParentView: View {@State private var text = ""var body: some View {VStack {Text("Parent: \(text)")ChildView(text: $text) // 傳遞綁定 }}
}struct ChildView: View {@Binding var text: String var body: some View {TextField("Enter text", text: $text)}
}

使用 @ObservedObject 和 @Published

class UserSettings: ObservableObject {@Published var score = 0 
}struct ContentView: View {@ObservedObject var settings = UserSettings()var body: some View {VStack {Text("Score: \(settings.score)")Button("Increase") {settings.score += 1 }}}
}

3. 列表與導航

動態列表

struct ContentView: View {let items = ["Apple", "Banana", "Cherry"]var body: some View {List(items, id: \.self) { item in Text(item)}}
}

帶刪除和移動功能的列表

struct ContentView: View {@State private var items = ["Apple", "Banana", "Cherry"]var body: some View {NavigationView {List {ForEach(items, id: \.self) { item in Text(item)}.onDelete(perform: deleteItems).onMove(perform: moveItems)}.navigationBarItems(trailing: EditButton())}}func deleteItems(at offsets: IndexSet) {items.remove(atOffsets: offsets)}func moveItems(from source: IndexSet, to destination: Int) {items.move(fromOffsets: source, toOffset: destination)}
}

4. 動畫與過渡

簡單動畫

@State private var scale: CGFloat = 1.0 var body: some View {Button("Tap Me") {withAnimation(.spring()) {scale = scale == 1.0 ? 2.0 : 1.0 }}.scaleEffect(scale)
}

自定義過渡

@State private var showDetails = false var body: some View {VStack {Button("Toggle") {withAnimation {showDetails.toggle()}}if showDetails {Text("Details").transition(.asymmetric(insertion: .move(edge: .leading),removal: .move(edge: .trailing)))}}
}

5. 實用修飾符

同時應用多個修飾符

Text("Hello").modifier(MyCustomModifier())// 或者使用擴展 
extension View {func customStyle() -> some View {self .padding().background(Color.blue).foregroundColor(.white).cornerRadius(10)}
}Text("Hello").customStyle()

條件修飾符

@State private var isHighlighted = false var body: some View {Text("Hello").foregroundColor(isHighlighted ? .red : .blue).onTapGesture {isHighlighted.toggle()}
}

6. 性能優化

使用 Lazy 視圖

ScrollView {LazyVStack { // 只渲染可見項 ForEach(0..<1000) { index in Text("Row \(index)")}}
}

使用 EquatableView 避免不必要重繪

struct UserView: View, Equatable {let user: User var body: some View {Text(user.name)}static func == (lhs: UserView, rhs: UserView) -> Bool {lhs.user.id == rhs.user.id }
}// 使用 
UserView(user: someUser).equatable()
  1. 與其他框架集成

與 UIKit 集成

struct MyUIKitView: UIViewRepresentable {func makeUIView(context: Context) -> UIActivityIndicatorView {UIActivityIndicatorView(style: .large)}func updateUIView(_ uiView: UIActivityIndicatorView, context: Context) {uiView.startAnimating()}
}// 使用 
MyUIKitView()

與 Core Data 集成

struct ContentView: View {@Environment(\.managedObjectContext) private var viewContext @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],animation: .default)private var items: FetchedResults<Item>var body: some View {List {ForEach(items) { item in Text("Item at \(item.timestamp!, formatter: itemFormatter)")}.onDelete(perform: deleteItems)}}private func deleteItems(offsets: IndexSet) {withAnimation {offsets.map { items[$0] }.forEach(viewContext.delete)try? viewContext.save()}}
}

8. 調試技巧

調試視圖層次結構

Text("Hello").debug() // 添加這個修飾符查看視圖信息 extension View {func debug() -> Self {print(Mirror(reflecting: self).subjectType)return self }
}

預覽多個設備

struct ContentView_Previews: PreviewProvider {static var previews: some View {Group {ContentView().previewDevice("iPhone 13")ContentView().previewDevice("iPhone SE (2nd generation)")ContentView().previewDevice("iPad Pro (12.9-inch) (5th generation)")}}
}

這些技巧可以幫助你更高效地使用 SwiftUI 構建應用程序。SwiftUI 仍在快速發展,建議定期查看 Apple 的官方文檔和 WWDC 會議視頻以獲取最新信息。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/87124.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/87124.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/87124.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

SpringMVC異步處理Servlet

使用SpringMVC異步處理Servlet解決的問題 可以不阻塞有限的tomcat 線程&#xff08;默認是200~250個&#xff0c;springboot3是200個&#xff09;&#xff0c;確保網絡請求可以持續響應特定業務使用自定義線程池&#xff0c;可以處理的業務量更大對上層業務完全無感知&#xf…

同步與異步編程范式全景研究——從CPU時鐘周期到云原生架構的范式演進

第一章 時空觀的根本分歧 1.1 物理時間的約束性 同步操作的本質是對牛頓絕對時間的服從&#xff0c;其阻塞特性源于馮諾依曼體系下指令順序執行的基因。現代CPU的流水線技術&#xff08;如Intel Hyper-Threading&#xff09;通過指令級并行實現偽異步&#xff0c;但開發者仍需…

【零散技術】5分鐘完成Odoo18 登陸頁面全自定義

序言:時間是我們最寶貴的財富,珍惜手上的每個時分 從最初的tinyERP到Open ERP&#xff0c;再由OpenERP到Odoo&#xff0c;雖然UI已經過了多次大改&#xff0c;Odoo登錄界面依舊丑陋&#xff0c;同時還有各種Odoo版權信息&#xff0c;對于定制項目而言是不友好的。 今天以Odoo18…

Vue3 + TypeScript + Element Plus + el-pagination 分頁查詢實例分享

前端技術棧&#xff1a;Vue3 TypeScript Element Plus el-pagination 后端技術棧&#xff1a;Java Spring Boot Mybatis 應用異常情況說明&#xff1a;點擊頁碼2&#xff0c;會發送兩次請求&#xff0c;并且自動跳回頁碼1 代碼&#xff1a; Reagent.vue <script set…

LoadRunner 2023 安裝部署

下載地址&#xff1a;鏈接: https://caiyun.139.com/w/i/2nQQRYCZ1Ssjl 提取碼:3gz0 復制內容打開139-云盤 主要下載Micro_Focus_LoadRunner_2023_Community_Edition.exe來安裝就可以。 如要漢化&#xff0c;則再下載安裝Language_Packs.exe的安裝包 說明&#xff1a;LoadR…

ABC410 : F - Balanced Rectangles

https://atcoder.jp/contests/abc410/tasks/abc410_fhttps://atcoder.jp/contests/abc410/tasks/abc410_f首先可以一眼看出暴力 &#xff1a;枚舉左上角和右下角&#xff0c;用前綴和算出矩形中#的數量&#xff0c;判斷即可 但這樣是,爆!!! 考慮優化&#xff0c;我們可以枚舉…

嵌入式學習筆記 - HAL庫對外設的封裝

一 外設封裝結構 HAL庫對外設的封裝使用了xx_HandleTypeDef類型的外設句柄結構體&#xff0c;這個句柄結構體的第一個成員Instance(xx_TypeDef類型)一般為該外設的所有寄存器的起始基地址&#xff0c;第二個成員Init&#xff08;xx_InitTypeDef類型&#xff09;一般為該外設的設…

高精度模板

加法 P1601 AB Problem&#xff08;高精&#xff09; #include<iostream>using namespace std; const int N 1e6 10; int a[N],b[N],c[N]; int len1,len2,lenMax; //長度要提前定義在全局&#xff0c;在函數中要使用 void add(int c[],int a[],int b[]) {for(int i0…

monorepo使用指北

| ?WARN? node_modules is present. Lockfile only installation will make it out-of-date ?ERR_PNPM_FETCH_404? GET https://registry.npmjs.org/common%2Fcommon: Not Found - 404 This error happened while installing a direct dependency of G:\monorepo\vue3 comm…

Java八股文——Spring「MyBatis篇」

與傳統的JDBC相比&#xff0c;MyBatis的優點&#xff1f; 面試官您好&#xff0c;MyBatis相比于傳統的JDBC&#xff0c;它并不是要完全顛覆JDBC&#xff0c;而是作為JDBC的一個強大的“增強框架”。它的核心價值在于&#xff0c;在保留了SQL最大靈活性的前提下&#xff0c;極大…

JavaScript基礎-常用的鼠標事件

一、前言 在前端開發中&#xff0c;鼠標事件 是實現用戶交互的重要手段之一。通過監聽用戶的點擊、移動、懸停等操作&#xff0c;我們可以構建出豐富而靈活的網頁交互體驗。 本文將帶你深入了解&#xff1a; JavaScript 中常見的鼠標事件&#xff1b;各類鼠標事件的觸發時機…

windows錄頻軟件

一.很反感有些做軟件的&#xff0c;把別人開源的改個界面收費&#xff0c;所以我找了一個開源免費的。 二.準備工具 一臺電腦&#xff0c; Captura:完全開源免費的錄頻軟件。 ffmpeg&#xff1a;音頻格式轉換軟件&#xff0c;這可是非常大名鼎鼎的工具。 三.安裝Captura 網址…

python中的模塊化編程:日期模塊、math算術模塊、random模塊

內置模塊&#xff08;math、random、時間&#xff09;自定義模塊&#xff08;自己寫的部分代碼&#xff09;第三方模塊&#xff08;引入的第三方代碼庫的模塊&#xff09; math模塊 import math#圓周率 print(math.pi) #自然常數 print(math.e) #圓周率的二倍 print(math.tau…

【學習筆記】Langchain基礎(二)

前文&#xff1a;【學習筆記】Langchain基礎 文章目錄 8 [LangGraph] 實現 Building Effective Agents&#xff0c;各種 workflows 及 AgentAugmented LLMPrompt ChainingParallelizationRoutingOrchestrator-Worker (協調器-工作器)Evaluator-optimizer (Actor-Critic)Agent 8…

Java大模型開發入門 (9/15):連接外部世界(中) - 向量嵌入與向量數據庫

前言 在上一篇文章中&#xff0c;我們成功地將一篇長文檔加載并分割成了一系列小的文本片段&#xff08;TextSegment&#xff09;。我們現在有了一堆“知識碎片”&#xff0c;但面臨一個新問題&#xff1a;計算機如何理解這些碎片的內容&#xff0c;并找出與用戶問題最相關的片…

Windows下MySQL安裝全流程圖文教程及客戶端使用指南(付整合安裝包)

本教程是基于5.7版本安裝&#xff0c;5.7和8.0的安裝過程大差不差 安裝包「windows上mysql中安裝包資源」 鏈接&#xff1a;https://pan.quark.cn/s/de275899936d 一、安裝前的準備 1.1 獲取 MySQL 安裝程序 官網 前往 MySQL 官方下載頁面&#xff0c;下載適用于 Windows 系…

筆記 軟件工程復習

第一章 軟件工程學概述 1.1 軟件危機&#xff08;Software Crisis&#xff09; 概念 定義&#xff1a;軟件危機指在計算機軟件開發與維護過程中遇到的一系列嚴重問題&#xff0c;源于1960年代軟件復雜度激增與傳統開發方法失效的矛盾。 本質&#xff1a;軟件規模擴大 → 開…

GaussDB創建數據庫存儲

示例一&#xff1a; 下面是一個簡單的GaussDB存儲過程示例&#xff1a; –創建一個存儲過程。 CREATE OR REPLACE PROCEDURE prc_add (param1 IN INTEGER,param2 IN OUT INTEGER ) AS BEGINparam2: param1 param2;dbe_output.print_line(result is: ||to_char(param…

基于51單片機的校園打鈴及燈控制系統

目錄 具體實現功能 設計介紹 資料內容 全部內容 資料獲取 具體實現功能 具體功能&#xff1a; &#xff08;1&#xff09;實時顯示當前時間&#xff08;年月日時分秒星期&#xff09;&#xff0c;LED模式指示燈亮。 &#xff08;2&#xff09;按下“打鈴”和“打鈴-”按鍵…

PHP+mysql雪里開輕量級報修系統 V1.0Beta

# PHP雪里開輕量級報修系統 V1.0Beta ## 簡介 這是一個基于PHP7和MySQL5.6的簡易報修系統&#xff0c;適用于學校、企業等機構的設備報修管理。 系統支持學生提交報修、后勤處理報修以及系統管理員管理用戶和報修記錄。 初代版本V1.0&#xff0c;尚未實際業務驗證&#xff0c;…