<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Labe on Medium]]></title>
        <description><![CDATA[Stories by Labe on Medium]]></description>
        <link>https://medium.com/@labcgood44?source=rss-544e92363ce9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YS-1atRZ5Fl2k6VO66w5bQ.jpeg</url>
            <title>Stories by Labe on Medium</title>
            <link>https://medium.com/@labcgood44?source=rss-544e92363ce9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 15:50:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@labcgood44/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ 42 請AI推薦Swift開發常用的第三方套件]]></title>
            <link>https://medium.com/@labcgood44/%E8%AB%8Bai%E6%8E%A8%E8%96%A6swift%E9%96%8B%E7%99%BC%E5%B8%B8%E7%94%A8%E7%9A%84%E7%AC%AC%E4%B8%89%E6%96%B9%E5%A5%97%E4%BB%B6-015782207c76?source=rss-544e92363ce9------2</link>
            <guid isPermaLink="false">https://medium.com/p/015782207c76</guid>
            <dc:creator><![CDATA[Labe]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 05:00:06 GMT</pubDate>
            <atom:updated>2025-01-23T11:25:49.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUAUD--NBL1f-3UppIycHg.png" /></figure><h4><strong>🙋🏻‍♀️ 什麼是第三方套件？</strong></h4><p>由非官方或非原始平台開發者所提供的軟體工具、程式碼庫或框架，用於幫助開發者快速實現某些功能，無需從頭編寫所有代碼。</p><h4><strong>🙋🏻‍♀️ 為什麼要使用第三套件？</strong></h4><p>在開發過程中，我們可以依靠自己所學把許多功能寫出來，而使用第三方套件可以省去自己開發的時間，直接使用現成的功能。</p><p>以網路請求作為範例（AI提供，使用Alamofire套件作示範）：</p><p>● 使用原生方式（URLSession）☟</p><pre>let url = URL(string: &quot;https://api.example.com/data&quot;)!<br><br>let task = URLSession.shared.dataTask(with: url) { data, response, error in<br>    if let error = error {<br>        print(&quot;Error: \(error.localizedDescription)&quot;)<br>        return<br>    }<br><br>    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {<br>        print(&quot;Invalid response&quot;)<br>        return<br>    }<br><br>    if let data = data {<br>        do {<br>            let json = try JSONSerialization.jsonObject(with: data, options: [])<br>            print(&quot;Response JSON: \(json)&quot;)<br>        } catch {<br>            print(&quot;JSON Parsing Error: \(error.localizedDescription)&quot;)<br>        }<br>    }<br>}<br><br>task.resume()</pre><p>● 使用Alamofire☟</p><pre>import Alamofire<br><br>AF.request(&quot;https://api.example.com/data&quot;).responseJSON { response in<br>    switch response.result {<br>    case .success(let data):<br>        print(&quot;Response JSON: \(data)&quot;)<br>    case .failure(let error):<br>        print(&quot;Error: \(error.localizedDescription)&quot;)<br>    }<br>}</pre><p>code明顯變得簡短且集中，開發時可以節省許多時間。</p><h4>🙋🏻‍♀️ 第三方套件這麼方便，那我還需要使用原生方法嗎？</h4><p>當然需要，沒有任何方法是完美的！<br>請ChatGPT來給我們講解一下兩者的差異☟</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*TCvGFraAsNr1Ei_hhawq9w.png" /></figure><p>任何人都可以開發第三方套件，所以你無法確認它是否安全，且不是所有套件都是免費的，使用時一定要多注意安全性、授權問題。<br>參考文章☟</p><ul><li><a href="https://www.gss.com.tw/gss-eis101/2895-eis101-8">管控行動應用程式的安全大小事 依靠第三方套件開發 行動應用程式錯了嗎？</a></li><li><a href="https://devco.re/blog/2014/03/14/3rd-party-software-security-issues/">使用第三方套件所要擔負的資安風險 | DEVCORE 戴夫寇爾</a></li></ul><p>了解完為何要使用第三方套件後，我請ChatGPT推薦我Swift開發常見的套件並放上研究的文章☟</p><h4>🪻 Alamofire</h4><p><strong>功能</strong>：<strong>處理 HTTP 請求</strong>，支持 JSON 解析、文件上傳/下載等。<br><strong>適用場景</strong>：簡化網路請求，取代原生 URLSession。</p><p><a href="https://franksios.medium.com/ios-%E4%BD%BF%E7%94%A8%E7%AC%AC%E4%B8%89%E6%96%B9%E5%A5%97%E4%BB%B6alamofire%E4%BE%86%E7%B0%A1%E5%8C%96%E7%B6%B2%E8%B7%AF%E5%8A%9F%E8%83%BD-38a1ef5b17fe">使用 Alamofire 來簡化與網路溝通的功能</a></p><h4>🪻RxSwift</h4><p><strong>功能</strong>：實現響應式編程，<strong>處理異步數據流</strong>。<br><strong>適用場景</strong>：處理複雜的異步操作，如連續網路請求、UI 更新等。</p><p><a href="https://beeth0ven.github.io/RxSwift-Chinese-Documentation/">RxSwift 中文文档</a></p><h4>🪻<strong>SwiftyJSON</strong></h4><p><strong>功能</strong>：<strong>簡化 JSON 的解析和處理</strong>。<br><strong>適用場景</strong>：需要解析 API 返回的 JSON 數據。</p><p><a href="https://franksios.medium.com/ios-%E4%BD%BF%E7%94%A8%E7%AC%AC%E4%B8%89%E6%96%B9%E5%A5%97%E4%BB%B6swiftyjson%E4%BE%86%E7%B0%A1%E5%8C%96%E5%8F%96%E5%BE%97%E7%9A%84json%E6%A0%BC%E5%BC%8F%E8%B3%87%E6%96%99-6edc48300333">使用第三方套件 SwiftyJSON 來簡化取得的 JSON 格式資料</a></p><h4>🪻<strong>Kingfisher</strong></h4><p><strong>功能</strong>：高效<strong>下載、快取圖片</strong>，支持 GIF 動圖。<br><strong>適用場景</strong>：需要處理網路圖片的應用。</p><p><a href="https://www.cnblogs.com/sundaysme/articles/10644466.html">Kingfisher的基本使用（一）</a></p><h4>🪻<strong>CryptoSwift</strong></h4><p><strong>功能</strong>：提供<strong>加密</strong>、哈希等功能，例如 AES、SHA256。<br><strong>適用場景</strong>：需要處理敏感數據的加密或驗證。</p><ul><li><a href="https://franksios.medium.com/ios-%E4%BD%BF%E7%94%A8aes%E6%96%B9%E5%BC%8F%E5%B0%87%E8%B3%87%E6%96%99%E5%8A%A0%E8%A7%A3%E5%AF%86-9fae62a48fc0">Swift 使用 AES 方式將資料加解密</a></li><li><a href="https://blog.csdn.net/u014599371/article/details/80195787">Swift - 第三方加密库CryptoSwift使用详解3（AES加密与解密）_swift aes ctr-CSDN博客</a></li></ul><h4>🪻<strong>Realm</strong></h4><p><strong>功能</strong>：<strong>輕量級資料庫</strong>，支持本地存儲和同步。<br><strong>適用場景</strong>：需要儲存結構化數據且對性能有要求。</p><p><a href="https://ithelp.ithome.com.tw/m/articles/10331885">iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></p><h4>🪻<strong>Eureka</strong></h4><p><strong>功能</strong>：快速構建表單界面，支持多種輸入類型。<br><strong>適用場景</strong>：需要處理多字段的輸入表單。</p><ul><li><a href="https://github.com/xmartlabs/Eureka/blob/master/Documentation/README_CN.md">Eureka/Documentation/README_CN.md at master · xmartlabs/Eureka</a></li><li><a href="https://anye3210.github.io/2019/06/04/Eureka%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89Cell/">【iOS】Eureka的基本使用和自定义Cell</a></li></ul><h4>🙋🏻‍♂️如何管理第三方套件？</h4><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E4%BD%BF%E7%94%A8-spm-%E5%AE%89%E8%A3%9D%E7%AC%AC%E4%B8%89%E6%96%B9%E5%A5%97%E4%BB%B6-xcode-11-%E6%96%B0%E5%8A%9F%E8%83%BD-2c4ffcf85b4b">使用 SPM 安裝第三方套件 — 以抓圖套件 Kingfisher 為例</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E4%BD%BF%E7%94%A8-cocoapods-%E7%AE%A1%E7%90%86%E7%AC%AC%E4%B8%89%E6%96%B9%E5%A5%97%E4%BB%B6-6e6135b62814">使用 CocoaPods 管理第三方套件</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=015782207c76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ 41 日記App-修改日記]]></title>
            <link>https://medium.com/@labcgood44/41-%E6%97%A5%E8%A8%98app-%E4%BF%AE%E6%94%B9%E6%97%A5%E8%A8%98-3aec6789db50?source=rss-544e92363ce9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aec6789db50</guid>
            <dc:creator><![CDATA[Labe]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 11:16:39 GMT</pubDate>
            <atom:updated>2025-01-10T11:23:46.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcE2Fe9QrAZxcNwwwYzMTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHDZBEKC4xgYJ75vo9wJrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fR_hPoFWOQfG8jWnhKCo-Q.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fkkey7w9R8jQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2Fkkey7w9R8jQ%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fkkey7w9R8jQ%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fb72a796218c213efe597ac2d6c4e64/href">https://medium.com/media/2fb72a796218c213efe597ac2d6c4e64/href</a></iframe><p>這次增加了修改日記的功能，日記App大致上就完成啦！</p><h4>💙 修改日記的方式：</h4><ol><li>日記的資料型態原本只有包含日期、圖片的URL、文字，這次新增了圖片上傳後的ID、日記上傳後的ID。</li><li>ID就是資料在firebase上的名字，利用ID就可以修改或刪除特定資料。</li><li>在編輯日記完成、按下儲存後，我會將舊有的日記刪除，新增新的日記。</li><li>因為圖片會先上傳在Storage，為了避免不需要的圖片一直留存在firebase上，所以圖片也要刪除。</li></ol><h4>💙 刪除資料</h4><p>Storage跟Firestore刪除資料都是使用各自的路徑+.delete方法。</p><p>這次有使用到do catch跟try await方法，因為有用到await（表明這是一個非同步操作，必須等待該操作完成後才能繼續執行後續程式碼），所以function需要加上async來表示函數裡包含非同步操作。</p><pre>func deleteOldData() async {<br>    // 刪除上傳的照片<br>    if let diaryImageID = showDairy.diaryImageID, let userID = Auth.auth().currentUser?.uid {<br>        let storegeRef = Storage.storage().reference().child(&quot;\(userID)/diary/\(diaryImageID)&quot;)<br>        storegeRef.delete { error in<br>            if let error {<br>                self.showAlert(title: &quot;錯誤&quot;, message: &quot;未成功刪除照片：\(error.localizedDescription)&quot;)<br>            } else {<br>                print(&quot;✓ 已刪除Storage圖片：\(diaryImageID)&quot;)<br>            }<br>        }<br>    }<br>    <br>    // 刪除上傳的日記<br>    if let diaryID = showDairy.diaryID, let userID = Auth.auth().currentUser?.uid {<br>        let db = Firestore.firestore()<br>        let diariesRef = db.collection(&quot;userDiaries&quot;).document(userID).collection(&quot;diaries&quot;).document(diaryID)<br>        do {<br>            try await diariesRef.delete()<br>            print(&quot;✓ 已刪除firestore日記資料：\(diaryID)&quot;)<br>        } catch {<br>            print(&quot;‼ 刪除firestore日記資料失敗，\(error.localizedDescription)&quot;)<br>        }<br>    }<br>}</pre><p>呼叫方法時需要用Task包裹執行，Task是用來管理非同步操作的工具。</p><pre>// 先判斷當前的日記是否為新增，如果不是就要先刪除資料<br>if isNewDiary == false {<br>    Task {<br>        await deleteOldData()<br>    }<br>}</pre><h4>💙 GitHub</h4><p><a href="https://github.com/labcgood/Life-Documentation">GitHub - labcgood/Life-Documentation</a></p><h4>💙 日記App文章</h4><ul><li><a href="https://medium.com/@labcgood44/38-life-documentation-app-%E8%A8%BB%E5%86%8A-%E7%99%BB%E5%85%A5-4b802d8ca224">🍀 38 日記App-註冊、登入</a></li><li><a href="https://medium.com/@labcgood44/39-life-documentation-app-%E4%B8%8A%E5%82%B3%E6%97%A5%E8%A8%98%E5%8A%9F%E8%83%BD-7959b7651af8">🍀 39 日記App-上傳日記</a></li><li><a href="https://medium.com/@labcgood44/40-textview-%E5%9C%A8%E9%8D%B5%E7%9B%A4%E4%B8%8A%E6%96%B9%E5%A2%9E%E5%8A%A0%E5%B7%A5%E5%85%B7%E5%88%97-e47d07c304c3">🍀 40 日記App-小功能紀錄</a></li></ul><p>如果有再增加有趣的功能再來分享，基本上算是完成了這個作品～</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aec6789db50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ 40 日記App-小功能紀錄]]></title>
            <link>https://medium.com/@labcgood44/40-textview-%E5%9C%A8%E9%8D%B5%E7%9B%A4%E4%B8%8A%E6%96%B9%E5%A2%9E%E5%8A%A0%E5%B7%A5%E5%85%B7%E5%88%97-e47d07c304c3?source=rss-544e92363ce9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e47d07c304c3</guid>
            <dc:creator><![CDATA[Labe]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 10:41:36 GMT</pubDate>
            <atom:updated>2025-01-10T11:23:15.462Z</atom:updated>
            <content:encoded><![CDATA[<p>延續上一篇文章，記錄一個小功能：在使用TextView編輯時，鍵盤上方增加工具列。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*rUJiwEy6cWeT9GJRVTyyMQ.gif" /></figure><p>在編輯TextView或TextField時，鍵盤上方自訂工具列，例如：利用上、下圖式來在各個文字編輯元件中轉跳、在編輯完成時收回鍵盤、使用相機圖示來新增圖片等等的功能，非常實用。</p><p>這次要示範的是簡單收回鍵盤功能，需要其他功能也可以套用，只要再改寫執行function就可以帶入各種功能啦～</p><h4>💙 生成UIBarButtonItem的方法</h4><pre>// 完成文字編輯後收起鍵盤的按鈕，這邊製作了一個文字跟一個圖示的版本<br>let doneButton = UIBarButtonItem(title: &quot;編輯完成&quot;, style: .done, target: self, action: #selector(dismissKeyboard))<br>let doneImageButton = UIBarButtonItem(image: UIImage(systemName: &quot;chevron.down&quot;), style: .done, target: self, action: #selector(dismissKeyboard))<br><br>// 用來佔位的靈活空間，排在最前面，讓其他按鈕可以靠右邊排列（沒有加的話靠左排列）<br>let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)</pre><p>● <strong>參數說明</strong></p><p><strong>title或image：</strong><br>外觀用文字或是圖示呈現。</p><p><strong>style：</strong><br>.plain→普通樣式，外觀最簡單、<br>.done→完成樣式，通常表示完成當前操作（按鈕文字會加粗，強調重要性）。<br>通常使用.done。</p><p><strong>target：</strong><br>按鈕的目標對象，當按鈕被點擊時，會在此對象上執行指定的動作方法。通常用self（當前的ViewController）。<br>這邊的範例flexibleSpace因為是來佔位用的，不需要目標對象，所以用nil。</p><p><strong>action：</strong><br>按鈕被點擊時觸發function。<br>#selector 是 Swift 中將方法名稱轉換為 Selector 的方式，用於指定目標方法。<br>要觸發的function前面需要使用<strong>@objc</strong>，需要執行的功能就寫在這邊，依照專案需求可以自訂，我們這邊要執行的是收回鍵盤的動作☟</p><pre>@objc func dismissKeyboard() {<br>    self.diaryTextView.resignFirstResponder()<br>}</pre><h4>💙 寫一個function來生成UIToolbar</h4><pre>func createToolbar() -&gt; UIToolbar {<br>    let toolbar = UIToolbar()<br>    toolbar.sizeToFit() //自動調整工具欄的大小以配合鍵盤的寬度。<br>    <br>    // 完成文字編輯後收起鍵盤的按鈕，這邊製作了一個文字跟一個圖示的版本<br>    let doneButton = UIBarButtonItem(title: &quot;編輯完成&quot;, style: .done, target: self, action: #selector(dismissKeyboard))<br>    let doneImageButton = UIBarButtonItem(image: UIImage(systemName: &quot;chevron.down&quot;), style: .done, target: self, action: #selector(dismissKeyboard))<br>    <br>    // 生出一個佔位空間，排在最前面，讓其他按鈕可以靠右邊排列<br>    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)<br>    <br>    // 設定按鈕顏色<br>    doneButton.tintColor = .black<br>    doneImageButton.tintColor = .black<br>    <br>    // 把剛剛生成的按鈕依序放進toolbar<br>    toolbar.items = [flexibleSpace, doneButton, doneImageButton]<br>    return toolbar<br>}<br><br>// 收起鍵盤<br>@objc func dismissKeyboard() {<br>    self.diaryTextView.resignFirstResponder()<br>}</pre><h4>💙 使用TextView的inputAccessoryView把生成的UIToolbar附加到TextView的輸入配件上（鍵盤）</h4><pre>// 在viewDidLoad裡使用<br>override func viewDidLoad() {<br>    super.viewDidLoad()<br>    <br>    diaryTextView.inputAccessoryView = createToolbar()<br>}</pre><p>這樣TextView的鍵盤上方就會出現自訂的工具列惹🥳</p><p>｡:.ﾟヽ(*´∀`)ﾉﾟ.:｡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e47d07c304c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ 39 日記App-上傳日記]]></title>
            <link>https://medium.com/@labcgood44/39-life-documentation-app-%E4%B8%8A%E5%82%B3%E6%97%A5%E8%A8%98%E5%8A%9F%E8%83%BD-7959b7651af8?source=rss-544e92363ce9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7959b7651af8</guid>
            <dc:creator><![CDATA[Labe]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 10:25:06 GMT</pubDate>
            <atom:updated>2025-01-10T11:22:47.655Z</atom:updated>
            <content:encoded><![CDATA[<p>這次完成了上傳日記的功能～</p><p>看一下成果畫面及操作☟</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*1XAL8FaweHl8AlYUEpIbiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K90YsMF2aPX3mJS4fbB2Cw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eLajcnm8fFOoFez1ej5UzA.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKdx8gBTazQ8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKdx8gBTazQ8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKdx8gBTazQ8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/833ace34d722dc42aefca005ae57f415/href">https://medium.com/media/833ace34d722dc42aefca005ae57f415/href</a></iframe><p>畫面好醜(*´艸`*)</p><h4>💙 步驟</h4><ol><li>做出新增日記的畫面，利用Firebase上傳資料的功能將日記資料上傳(相片要先上傳，再取得URL，再跟日記日期及文字一起上傳到Cloud Firestore)。</li><li>成功上傳日記後，回到主頁顯示上傳的日記。</li><li>主頁右上角新增了navigationItem.rightBarButtonItem，結合UIMenu做出選單按鈕(Pull Down Button)，把原本臨時的登出功能放進去，未來還可以增加需要的功能。</li></ol><h4>💙 上傳資料</h4><p>上傳跟下載資料花了不少時間研究，我的理解是collection裡只能放入document，不能再放collection，但document中可以放入collection，這邊放入我的Code來示範一下</p><pre>// 取得 userID等等比較方便使用       <br>let userID = Auth.auth().currentUser?.uid ?? &quot;&quot; <br><br>// 初始化 Cloud Firestore<br>let db = Firestore.firestore() <br><br>// 設定要儲存資料的路徑<br>// 我希望在 userDiaries集合中的 userID文件裡面用一個子集合 diaries存取我的每篇日記<br>let diariesRef = db.collection(&quot;userDiaries&quot;).document(userID).collection(&quot;diaries&quot;)<br><br>// 使用addDocument方法來在子集合diaries底下新增文件(document)<br>diariesRef.addDocument(data: [String : Any], completion: (((any Error)?) -&gt; Void)?)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrM4SWnVe8JZNHo7uT103Q.png" /></figure><p>我一開始想用userID來放userDiaries，在userDiaries裡存多篇日記，想當然是失敗了，腦袋就有點卡住，但其實就只是你要遵循他的規則去建立資料夾，而不是自己想怎麼存就怎麼存，我的這個想法的話就會少一層路徑，我是想用collection → collection → document的方式存，但是Firestore規定collection後面要有document，資料夾結構應該要長這樣collection → document → collection → document，路徑要是偶數，不然就會報錯：<em>’FIRInvalidArgumentException’, reason: ‘Invalid document reference. Document references must have an even number of segments, but userDiaries/UaplKO5pLdQlEAhTRaU48Ufmgzh1/2024–12–07–63C42EA3–180E-4415–92A1-D1490C25D133 has 3’(文件引用無效，因為它的路徑片段數量不是偶數)</em>。</p><p>*上一篇其實就有用到上傳資料的方法了，只是因為那時候上傳的使用者資訊比較簡單，所以沒有遇到這個問題。</p><h4>💙 下載資料</h4><p>跟上傳資料一樣也有路徑問題，所以也要注意，在上傳時就要想到下載時的路徑問題，存在方便下載的。</p><pre>// 取得 userID等等比較方便使用       <br>let userID = Auth.auth().currentUser?.uid ?? &quot;&quot; <br><br>// 初始化 Cloud Firestore<br>let db = Firestore.firestore()<br><br>// 建立要取得資料的路徑<br>let userDiariesRef = db.collection(&quot;userDiaries&quot;).document(userID).collection(&quot;diaries&quot;)<br><br>// 使用getDocuments方法來取得所有存放日記的document<br>userDiariesRef.getDocuments(completion: &lt;(QuerySnapshot?, (any Error)?) -&gt; Void&gt;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*uh32dHLTNuY1lmUrcvvM8w.png" /></figure><p>關於上傳跟下載，在firebase的文件中也有範例可以參考。<br>firebase範例是使用do-catch的方式處理addDocument及getDocuments結果，我的Code是使用了閉包回調的方法來處理，之後應該會再改成do-catch的方式😣</p><ul><li><a href="https://firebase.google.com/docs/firestore/manage-data/add-data?hl=zh-tw">將資料新增至 Cloud Firestore | Firebase</a></li><li><a href="https://firebase.google.com/docs/firestore/query-data/get-data?hl=zh-tw">透過 Cloud Firestore 取得資料 | Firebase</a></li></ul><h4>💙新增有選單功能的navigationItem.rightBarButtonItem</h4><pre>// 先建立想要顯示的選單(UIMenu)，將UIAction放入children陣列裡，UIAction的handler寫入選取後要做的事情<br>// 我目前只有登出功能，所以UIAction只有放一個<br>let menu = UIMenu(children: [<br>    UIAction(title: &quot;登出&quot;, image: UIImage(systemName: &quot;iphone.and.arrow.right.outward&quot;), handler: { action in<br>        // 使用者登出<br>        do {<br>            try Auth.auth().signOut()<br>            print(&quot;\(Auth.auth().currentUser?.uid ?? &quot;&quot;)已登出&quot;)<br>        } catch {<br>            self.showAlert(title: &quot;錯誤&quot;, message: error.localizedDescription)<br>        }<br>        <br>        // 返回登入畫面<br>        self.performSegue(withIdentifier: &quot;toLogInViewController&quot;, sender: self)<br>    })<br>])<br><br>// 生成一個UIBarButtonItem，用圖片來顯示(也可以用文字)，再加入剛剛建立的Menu<br>let saveButton = UIBarButtonItem(image: UIImage(systemName: &quot;gearshape&quot;), menu: menu)<br><br>// 設定按鈕顏色<br>saveButton.tintColor = .white<br><br>// 把按鈕加入navigationItem的右邊<br>navigationItem.rightBarButtonItem = saveButton</pre><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/ios-%E7%9A%84%E9%81%B8%E5%96%AE-menu-%E6%8C%89%E9%88%95-pull-down-button-pop-up-button-2ddab2181ee5">iOS 的選單(menu)按鈕 — Pull Down Button &amp; Pop Up Button</a></p><p>💙GitHub</p><p><a href="https://github.com/labcgood/Life-Documentation?source=post_page-----4b802d8ca224--------------------------------">GitHub - labcgood/Life-Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7959b7651af8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ 38 日記App-註冊、登入]]></title>
            <link>https://medium.com/@labcgood44/38-life-documentation-app-%E8%A8%BB%E5%86%8A-%E7%99%BB%E5%85%A5-4b802d8ca224?source=rss-544e92363ce9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b802d8ca224</guid>
            <dc:creator><![CDATA[Labe]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 10:43:25 GMT</pubDate>
            <atom:updated>2025-01-10T11:22:33.280Z</atom:updated>
            <content:encoded><![CDATA[<p>來練習使用強大的firebase，這次目標是做一個生活紀錄的App！<br>目前完成了註冊跟登入的功能，先來看看成果☟</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*NudouNAo1mTloG2bVDL6pA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*KyuKp400TavUQBOfnVLIuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*4ojqiVpo6Ie84gdtv_B7qA.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fkj2A-91N2Qo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dkj2A-91N2Qo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fkj2A-91N2Qo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdca7d90be4ed20eee0a2edfef207c8d/href">https://medium.com/media/fdca7d90be4ed20eee0a2edfef207c8d/href</a></iframe><p>執行出來的元件、文字顏色一直亂跳🫠<br>主要是功能能用就好，這問題先放水流,,Ծ‸Ծ,,</p><h4>💙 步驟</h4><ol><li>先註冊Firebase，連接專案、安裝套件。</li><li>設置好App畫面（基本：輸入註冊資料的TextField跟登入、登出按鍵）。</li><li>使用Authentication來做出註冊、登入、登出等功能。</li><li>使用Storage上傳圖片並取得URL。</li><li>使用Cloud Firestore上傳使用者資訊，讓使用者登入後可以抓取資料，並顯示在頁面上（使用者名稱、使用者設定的頭貼圖片等）。</li><li>Firebase的相關設定可以參考以下文章～</li></ol><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%BB%BA%E7%AB%8B-firebase-%E5%B0%88%E6%A1%88-fbd6d19808c3">建立 Firebase 專案</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E8%A8%AD%E5%AE%9A-ios-app-%E7%9A%84-firebase-%E5%8A%9F%E8%83%BD-afcaaabe00f2">設定 iOS App 的 Firebase 功能和安裝 Firebase 套件</a></li></ul><p>Firebase功能文件說明☟</p><p><a href="https://firebase.google.com/docs/auth?hl=zh-tw">Firebase Authentication</a></p><h4>💙 Code</h4><ul><li>User。</li></ul><pre>// 從firebase下載使用者資料時可以建立User儲存資料<br>struct User {<br>    var userName: String?<br>    var userProfileImageUrlString: String?<br>}</pre><ul><li>Utils：擴展ViewController，方便使用重複性高的方法。</li></ul><ol><li>偵測鍵盤彈出時是否擋住輸入框。</li><li>顯示警告、通知的UIAlertController。</li></ol><pre>import UIKit<br><br>// 因為偵測鍵盤的方法在很多地方都可以用到，如果在每個controller都要寫一次的話會讓code太多，所以直接用擴展的方式處理<br>// 擴展 UIViewController，用來處理鍵盤通知<br>extension UIViewController {<br>    <br>    // 設置鍵盤通知，讓子類別可以方便地使用「根據鍵盤的顯示、收起的動作來決定移動View」的方法<br>    func setKeyboardNotification() {<br>        let center = NotificationCenter.default<br>        center.addObserver(self, selector: #selector(keyboardShown), name: UIResponder.keyboardWillShowNotification, object: nil)<br>        center.addObserver(self, selector: #selector(keyboardHidden), name: UIResponder.keyboardWillHideNotification, object: nil)<br>    }<br>    <br>    // 鍵盤出現時將 view 上移<br>    @objc func keyboardShown(notification: Notification) {<br>        guard let activeTextField = findActiveTextField(in: self.view) else { return }<br>        <br>        let info = notification.userInfo! as NSDictionary<br>        let keyboardSize = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue<br>        let keyboardTopY = self.view.frame.height - keyboardSize.height<br>        let editingTextFieldBottomY = activeTextField.convert(activeTextField.bounds, to: self.view).maxY<br>        let targetY = editingTextFieldBottomY - keyboardTopY<br>        <br>        if self.view.frame.minY &gt;= 0 {<br>            if targetY &gt; 0 {<br>                UIView.animate(withDuration: 0.25) {<br>                    self.view.frame = CGRect(x: 0, y: -(targetY + 80), width: self.view.frame.width, height: self.view.frame.height)<br>                }<br>            }<br>        }<br>    }<br>    <br>    // 鍵盤隱藏時將 view 移回原位<br>    @objc func keyboardHidden(notification: Notification) {<br>        UIView.animate(withDuration: 0.25) {<br>            self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)<br>        }<br>    }<br>    <br>    // 尋找當前使用的 UITextField<br>    private func findActiveTextField(in view: UIView) -&gt; UITextField? {<br>        // 利用迴圈尋找正在活動中的view<br>        for subview in view.subviews {<br>            // 如果活動中的view是UITextField的話，就回傳<br>            if let textField = subview as? UITextField, textField.isFirstResponder {<br>                return textField<br>                // 如果不是的話就再調用一次自己(function)尋找子view中的子view是不是UITextField，找到就回傳<br>            } else if let foundTextField = findActiveTextField(in: subview) {<br>                return foundTextField<br>            }<br>        }<br>        return nil<br>    }<br>}<br><br><br><br>// 因為重複在各個View Controller中使用到AlertController，且用法簡單，所以直接擴展在UIViewController裡方便使用<br>extension UIViewController {<br>    // 顯示提示、警告<br>    func showAlert(title: String?, message: String?) {<br>        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)<br>        alert.addAction(UIAlertAction(title: &quot;好的&quot;, style: .default))<br>        present(alert, animated: true)<br>    }<br>}</pre><ul><li>RegisterViewController：註冊功能。</li></ul><pre>import UIKit<br>import Firebase<br>import FirebaseAuth<br>import FirebaseStorage<br><br>class RegisterViewController: UIViewController {<br>    <br>    @IBOutlet weak var profileImageView: UIImageView!<br>    @IBOutlet weak var addImageButton: UIButton!<br>    @IBOutlet weak var frameView: UIView!<br>    @IBOutlet weak var signUpButton: UIButton!<br>    <br>    @IBOutlet weak var nameTextField: UITextField!<br>    @IBOutlet weak var emailTextField: UITextField!<br>    @IBOutlet weak var passwordTextField: UITextField!<br>    @IBOutlet weak var checkPasswordTextField: UITextField!<br>    <br>    var haveProfileImage = false<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setKeyboardNotification() //監聽鍵盤活動<br>        updateUI() //初始化畫面<br>    }<br>    <br>    // 點空白處收鍵盤<br>    override func touchesEnded(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>        view.endEditing(true)<br>    }<br>    <br>    // 設定UI<br>    func updateUI() {<br>        // 頭貼imageView設定<br>        profileImageView.clipsToBounds = true<br>        profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2<br>        <br>        // 輸入框背景view設定<br>        frameView.clipsToBounds = true<br>        frameView.layer.cornerRadius = 10<br>    }<br>    <br>    // 選擇頭貼<br>    @IBAction func selectProfilePic(_ sender: Any) {<br>        let controller = UIImagePickerController()<br>        controller.delegate = self<br>        present(controller, animated: true)<br>    }<br>    <br>    // 註冊帳號<br>    @IBAction func signUp(_ sender: Any) {<br>        <br>        // 先判斷密碼與確認密碼是否一致、是否設定頭貼、資料是否皆填妥<br>        // 以上沒有問題就呼叫registerUser來註冊帳號<br>        if passwordTextField.text != checkPasswordTextField.text {<br>            showAlert(title: &quot;密碼確認失敗&quot;, message: &quot;請檢查密碼是否輸入一致&quot;)<br>            print(&quot;密碼確認失敗&quot;)<br>        } else if haveProfileImage == false {<br>            showAlert(title: &quot;請設定頭貼&quot;, message: nil)<br>            print(&quot;未設定頭貼&quot;)<br>        } else {<br>            // 先檢查使用者是否已填妥資料，並取得TextField輸入的資料<br>            guard let name = nameTextField.text, !name.isEmpty,<br>                  let email = emailTextField.text, !email.isEmpty,<br>                  let password = passwordTextField.text, !password.isEmpty else {<br>                showAlert(title: &quot;資料填寫不完整&quot;, message: nil)<br>                print(&quot;資料填寫不完整&quot;)<br>                return<br>            }<br>            registerUser(name: name, email: email, password: password)<br>        }<br>    }<br>    <br>    // 創建使用者 - 在「註冊帳號」Button裡呼叫<br>    func registerUser(name: String ,email: String, password: String) {<br>        <br>        // 使用Auth.auth()的createUser方法來註冊使用者（這是Firebase的方法）<br>        Auth.auth().createUser(withEmail: email, password: password) { authResult, error in<br>            // 通知：註冊失敗<br>            if let error {<br>                self.showAlert(title: &quot;註冊失敗&quot;, message: error.localizedDescription)<br>                print(&quot;註冊失敗：\(error.localizedDescription)&quot;)<br>                return<br>            }<br>            <br>            // 通知：註冊成功<br>            self.showAlert(title: &quot;註冊成功&quot;, message: nil)<br>            print(&quot;註冊成功，使用者ID：\(authResult?.user.uid ?? &quot;&quot;)&quot;)<br>            <br>            // 確保資料（為了方便使用資料，這邊都先用guard let做確保）<br>            // 在「註冊帳號」Button裡會確定使用者有選取頭貼<br>            guard let profileImage = self.profileImageView.image else {<br>                print(&quot;錯誤：頭貼缺失&quot;)<br>                return<br>            }<br>            // 上面已經註冊成功，這邊應該要有使用者 ID，所以使用 authResult來取得 ID<br>            guard let userID = authResult?.user.uid else {<br>                print(&quot;錯誤：無法取得使用者ID&quot;)<br>                return<br>            }<br>            <br>            // 呼叫上傳頭貼的function，以取得頭貼的url<br>            // 用switch方法來判斷成功跟失敗要做什麼事<br>            self.uploadProfileImage(userID: userID, profileImage: profileImage) { result in<br>                switch result {<br>                // 成功：取得 url後就呼叫 saveUserInfo方法，將使用者的 userName跟 profileImageUrl上傳到 firestore database裡儲存，方便以後使用者登入都可以抓取使用<br>                case .success(let profileImageUrlString):<br>                    self.saveUserInfo(userID: userID, userName: name, profileImageUrlString: profileImageUrlString) { error in<br>                        if let error {<br>                            print(&quot;使用者資料儲存失敗：\(error.localizedDescription)&quot;)<br>                        } else {<br>                            print(&quot;使用者資料儲存成功&quot;)<br>                            self.performSegue(withIdentifier: &quot;registerSuccsToDiaryViewController&quot;, sender: self)<br>                        }<br>                    }<br>                // 失敗：報錯<br>                case .failure(let error):<br>                    print(&quot;錯誤（頭貼上傳失敗）：\(error.localizedDescription)&quot;)<br>                }<br>            }<br>        }<br>    }<br>    <br>    // 上傳頭貼圖片<br>    func uploadProfileImage(userID: String, profileImage: UIImage, completion: @escaping (Result&lt;String, Error&gt;) -&gt; Void) {<br>        // 建立 storage文件夾<br>        let storageRef = Storage.storage().reference().child(&quot;userInfo/\(userID)/profilePicture.jpg&quot;)<br>        <br>        // 將 UIImage轉換成 JPEG格式的 Data，以便上傳<br>        // compressionQuality設定為 0.8，表示圖像的壓縮品質為 80%。數值範圍是 0.0 到 1.0，數值越高，品質越好，檔案越大<br>        guard let imageData = profileImage.jpegData(compressionQuality: 0.8) else {<br>            completion(.failure(NSError(domain: &quot;InvalidImage&quot;, code: 400, userInfo: [NSLocalizedDescriptionKey: &quot;Unable to process image&quot;])))<br>            return<br>        }<br>        <br>        // putData 是 Firebase Storage 上傳檔案的 API，這裡上傳 imageData（圖片的二進位資料），metadata 為 nil，表示不額外指定任何檔案的 Meta 資訊<br>        storageRef.putData(imageData, metadata: nil) { metadata, error in<br>            if let error {<br>                completion(.failure(error))<br>                print(&quot;錯誤（頭貼上傳失敗）：\(error.localizedDescription)&quot;)<br>                return<br>            }<br>            <br>            // 上傳成功後，要取得頭貼的url，downloadURL是 Firebase Storage提供的 API，用於取得上傳檔案的公開訪問 url<br>            storageRef.downloadURL { url, error in<br>                // 失敗：報錯<br>                if let error {<br>                    completion(.failure(error))<br>                    print(&quot;錯誤（頭貼url取得失敗）：\(error.localizedDescription)&quot;)<br>                    return<br>                }<br>                // 成功：成功取得url的字串後，返回該 url給調用方<br>                if let downloadURLString = url?.absoluteString {<br>                    completion(.success(downloadURLString))<br>                    print(&quot;頭貼上傳成功&quot;)<br>                }<br>            }<br>        }<br>    }<br>    <br>    // 儲存使用者資料到firebase(存到firestore database裡)<br>    func saveUserInfo(userID: String, userName: String, profileImageUrlString: String, completion: @escaping (Error?) -&gt; Void) {<br>        // 在firestore建立資料夾<br>        let db = Firestore.firestore()<br>        let userRef = db.collection(&quot;userInfo&quot;).document(userID)<br>        <br>        // 要儲存的資料<br>        let userInfo: [String: Any] = [<br>            &quot;userName&quot;: userName,<br>            &quot;profileImageUrl&quot;: profileImageUrlString<br>        ]<br>        <br>        // 將資料儲存進去<br>        userRef.setData(userInfo) { error in<br>            completion(error)<br>        }<br>    }<br>}<br><br><br>// 擴展RegisterViewController，取得選取相片的功能<br>extension RegisterViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {<br>    <br>    // 從相簿裡選擇頭貼相片<br>    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {<br>        profileImageView.image = info[.originalImage] as? UIImage<br>        haveProfileImage = true<br>        dismiss(animated: true)<br>    }<br>}</pre><ul><li>LogInViewController：登入功能。</li></ul><pre>import UIKit<br>import Firebase<br>import FirebaseAuth<br><br>class LogInViewController: UIViewController {<br><br>    @IBOutlet weak var frameView: UIView!<br>    <br>    @IBOutlet weak var emailTextField: UITextField!<br>    @IBOutlet weak var passwordTextField: UITextField!<br>    <br>    let auth = Auth.auth()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setKeyboardNotification() //監聽鍵盤活動<br>        updateUI() //初始化畫面<br>        isUserLogIn() //判斷是否有使用者登入中<br>    }<br>    <br>    // 點空白處收鍵盤<br>    override func touchesEnded(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>        view.endEditing(true)<br>    }<br><br>    // 設定UI<br>    func updateUI() {<br>        // 輸入框背景view設定<br>        frameView.clipsToBounds = true<br>        frameView.layer.cornerRadius = 10<br>        <br>        // 隱藏返回鍵<br>        self.navigationItem.hidesBackButton = true<br>    }<br>    <br>    // 判斷是否有使用者登入，如果已登入狀態就直接進入日記頁面<br>    func isUserLogIn() {<br>        if auth.currentUser == nil {<br>            print(&quot;目前沒有用戶登入，用戶ID：\(auth.currentUser?.uid ?? &quot;&quot;)&quot;)<br>            return<br>        } else {<br>            print(&quot;用戶\(auth.currentUser?.uid ?? &quot;&quot;)登入中&quot;)<br>            self.performSegue(withIdentifier: &quot;logInSuccsToDiaryViewController&quot;, sender: self)<br>        }<br>    }<br>    <br>    // 登入功能 - 在「登入」Button裡呼叫<br>    func logIn(email: String, password: String) {<br>        // 使用signIn方法來登入使用者（這是Firebase的方法）<br>        auth.signIn(withEmail: email, password: password) { Result, error in<br>            if let error {<br>                print(&quot;登入失敗：\(error.localizedDescription)&quot;)<br>                print(&quot;email:\(email),password:\(password)&quot;)<br>                self.showAlert(title: &quot;錯誤&quot;, message: error.localizedDescription)<br>            } else {<br>                print(&quot;用戶登入成功，ID：\(self.auth.currentUser?.uid ?? &quot;&quot;)&quot;)<br>                self.performSegue(withIdentifier: &quot;logInSuccsToDiaryViewController&quot;, sender: self)<br>            }<br>        }<br>    }<br>    <br>    // 登入（ 呼叫logIn() ）<br>    @IBAction func logIn(_ sender: Any) {<br>        // 確保資料填寫完整<br>        guard let email = emailTextField.text, !email.isEmpty,<br>              let password = passwordTextField.text,!password.isEmpty else {<br>            self.showAlert(title: &quot;資料填寫不完整&quot;, message: nil)<br>            return<br>        }<br>        logIn(email: email, password: password)<br>    }<br>}</pre><ul><li>DiaryViewController ：日記頁面-目前功能僅有顯示使用者資訊、臨時登出鍵。</li></ul><pre>import UIKit<br>import FirebaseFirestore<br>import Firebase<br>import FirebaseAuth<br>import SDWebImage<br><br>class DiaryViewController: UIViewController {<br><br>    @IBOutlet weak var profileImageView: UIImageView!<br>    @IBOutlet weak var userNameLabel: UILabel!<br>    <br>    let auth = Auth.auth()<br>    var user: User?<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        // 隱藏返回鍵<br>        self.navigationItem.hidesBackButton = true<br>        updateUI()<br>        <br>        // 確保 userID存在，呼叫 fetchUserInfo方法抓取使用者資訊(userInfo)，成功後呼叫updateUserInfo來更新畫面<br>        guard let userID = auth.currentUser?.uid else {<br>            print(&quot;錯誤：未找到使用者 ID&quot;)<br>            return<br>        }<br>        fetchUserInfo(userID: userID) { result in<br>            switch result {<br>            case .success(let user):<br>                self.updateUserInfo(user: user)<br>            case .failure(let error):<br>                print(&quot;錯誤：\(error.localizedDescription)&quot;)<br>            }<br>        }<br>    }<br>    <br>    // 取得上傳到firebase上的userInfo<br>    func fetchUserInfo(userID: String, completion: @escaping (Result&lt;User, Error&gt;) -&gt; Void) {<br>        // 取得 Firestore 資料庫的引用<br>        let db = Firestore.firestore()<br>        // 指定要取得的文件路徑：userInfo集合下特定 userID的文件<br>        let userRef = db.collection(&quot;userInfo&quot;).document(userID)<br>        <br>        // 使用.getDocument從 Firestore 下載該文件的資料<br>        userRef.getDocument { document, error in<br>            if let error {<br>                print(&quot;錯誤（下載使用者資料失敗）：\(error.localizedDescription)&quot;)<br>                completion(.failure(error))<br>                return<br>            }<br>            <br>            // 確認文件存在：document.exists是用來表示文件是否存在的屬性<br>            guard let document = document, document.exists else {<br>                print(&quot;錯誤：文件不存在&quot;)<br>                completion(.failure(NSError(domain: &quot;DocumentNotFound&quot;, code: 404, userInfo: [NSLocalizedDescriptionKey: &quot;User document not found&quot;])))<br>                return<br>            }<br>            <br>            // 取得資料後，解析資料<br>            let data = document.data()<br>            let userName = data?[&quot;userName&quot;] as? String<br>            let profileImageUrlString = data?[&quot;profileImageUrl&quot;] as? String<br>            <br>            // 將資料存給user<br>            let user = User(userName: userName, userProfileImageUrlString: profileImageUrlString)<br>            self.user = user<br>            <br>            // 如果成功抓取到資料，透過 completion 回傳成功，並傳遞 User物件<br>            completion(.success(user))<br>            print(&quot;使用者資料下載成功：\(user)&quot;)<br>        }<br>    }<br>    <br>    // 更新畫面上的使用者資訊（頭貼跟名稱）<br>    func updateUserInfo(user: User) {<br>        print(&quot;使用者名稱：\(user.userName ?? &quot;&quot;)&quot;)<br>        profileImageView.sd_setImage(with: URL(string: user.userProfileImageUrlString ?? &quot;&quot;))<br>        userNameLabel.text = &quot;\(user.userName ?? &quot;&quot;)的日記&quot;<br>    }<br>    <br>    // 設定UI<br>    func updateUI() {<br>        profileImageView.clipsToBounds = true<br>        profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2<br>    }<br>    <br>    // 登出<br>    @IBAction func logOut(_ sender: Any) {<br>        do {<br>            try auth.signOut()<br>            print(&quot;\(auth.currentUser?.uid ?? &quot;&quot;)已登出&quot;)<br>        } catch {<br>            let alert = UIAlertController(title: &quot;錯誤&quot;, message: error.localizedDescription, preferredStyle: .alert)<br>            alert.addAction(UIAlertAction(title: &quot;OK&quot;, style: .default))<br>            self.present(alert, animated: true)<br>        }<br>        <br>        // 返回登入畫面<br>        performSegue(withIdentifier: &quot;toLogInViewController&quot;, sender: self)<br>    }<br>}</pre><h4>💙 參考文章</h4><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/18-1-%E5%88%A9%E7%94%A8firebase%E8%A3%BD%E4%BD%9C-ios-app-%E7%9A%84%E7%99%BB%E5%85%A5%E8%A8%BB%E5%86%8A%E5%8A%9F%E8%83%BD-%E6%8A%93%E5%8F%96lorem-picsum-api%E5%9C%96%E7%89%87%E8%A8%AD%E5%AE%9A%E4%BD%BF%E7%94%A8%E8%80%85%E7%85%A7%E7%89%87-%E4%B8%A6%E8%87%AA%E8%A3%BD%E7%B0%A1%E5%96%AE%E7%9A%84%E8%AE%80%E5%8F%96%E5%8B%95%E7%95%AB-8160a7764104">#18–1-利用Firebase製作 iOS App 的登入註冊功能，抓取Lorem Picsum API圖片設定使用者照片，並自製簡單的讀取動畫</a></p><h4>💙 GitHub</h4><p><a href="https://github.com/labcgood/Life-Documentation">GitHub - labcgood/Life-Documentation</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b802d8ca224" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ 37 訂飲料App-串接API]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/37-%E8%A8%82%E9%A3%B2%E6%96%99app-%E4%B8%B2%E6%8E%A5api-0e4d95e2c17b?source=rss-544e92363ce9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e4d95e2c17b</guid>
            <dc:creator><![CDATA[Labe]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 16:24:55 GMT</pubDate>
            <atom:updated>2025-01-10T11:21:32.576Z</atom:updated>
            <content:encoded><![CDATA[<p>今天要來分享App的最後一步，串接API抓取菜單資料及上傳訂單。<br>我的App運行是先讓使用者點餐，飲料加入購物車後會將資料存在App裡，關掉App也不會消失，在購物車確認、修改訂單後送出訂單，就會將訂單資料傳到Airtable，並清除App裡的資料。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ucCXM72eXv30vjNGkv97aA.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fw1JLEDKys_8&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dw1JLEDKys_8&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2Fw1JLEDKys_8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bffc1fcbd8d3ab294225334ddd62a782/href">https://medium.com/media/bffc1fcbd8d3ab294225334ddd62a782/href</a></iframe><h3>💙 步驟</h3><p>這個App的製作我是先把素材都存在App裡做使用(菜單、圖片等)，所以這次要把原本的素材給拿掉，換成使用API抓下來的資料。</p><p>● 建立Airtable的table，將菜單輸入上去，另外在建立一個table用來存上傳的資料（Airtable的使用可以跟著下面放的參考文章操作，Peter寫得非常清楚🥹）。</p><p>● 取得API網址跟Token後在Postman測試，取得資料後轉成JAON，在專案中創建相對應的struct，以接應資料。</p><p>● 上傳的資料也要創建相對應的struct，才能上傳成功。</p><p>● 增加暫存資料功能。</p><p>●防止API key上傳到 GitHub。</p><h3>💙 Code</h3><p>● Model 修改</p><p>1. Drink struct<br>在App製作中不斷的被修改😂像是中間加了顯示飲料介紹的detail，或是為了判斷是否能做熱飲的makeHot等屬性，這次也為了要接資料被修改。</p><pre>import Foundation<br>import UIKit<br><br>struct Menu:Codable {<br>    let records:[Record]<br>}<br><br>struct Record:Codable {<br>    let fields:ResponseDrink<br>}<br><br>struct ResponseDrink:Codable {<br>    let type: DrinkType<br>    let name: String<br>    let largePrice: Int<br>    let middlePrice: Int<br>    let detail: String<br>    let makeHot: Bool?<br>    let image: [Image]<br>}<br><br>struct Image: Codable {<br>    let url: String<br>}<br>-----------------------------------------------------------------------------<br>struct Drink:Codable {<br>    let type: DrinkType<br>    let name: String<br>    let largePrice: Int<br>    let middlePrice: Int<br>    let detail: String<br>    let makeHot: Bool<br>    let image: Image<br>}<br><br>// 方便輸入茶品種類及減少打字錯誤<br>enum DrinkType:String, Codable {<br>    case 季節限定, 單品茶, 調茶, 雲蓋, 歐蕾<br>}<br><br>// 用於選取Button時的判斷（增加可讀性）<br>enum DrinkOption:Int {<br>    case 季節限定, 單品茶, 調茶, 雲蓋, 歐蕾<br>}<br><br>var drinks:[Drink] = []</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*Jl3c6rj0kTFgOlrGoa1txw.png" /><figcaption>轉成JSON的資料(可以對照著看)</figcaption></figure><p>2. ShoppingCart Class<br>增加了儲存功能(存在購物車的資料)</p><pre>class ShoppingCart {<br>    static let shared = ShoppingCart()<br>    <br>    private init() {<br>        cartItems = ShoppingCart.load() ?? []<br>    }<br>    <br>    var cartItems:[OrderDrink] = [] {<br>        didSet {<br>            ShoppingCart.save(item: cartItems)<br>        }<br>    }<br>    <br>    // 購物車的商品暫存在App裡，以免關掉App時被清空<br>    static let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!<br>    <br>    static func save(item: [OrderDrink]) {<br>        guard let data = try? JSONEncoder().encode(item) else { return }<br>        let url = documentsDirectory.appendingPathComponent(&quot;cartItems&quot;)<br>        try? data.write(to: url)<br>    }<br>    <br>    static func load() -&gt; [OrderDrink]? {<br>        let url = documentsDirectory.appendingPathComponent(&quot;cartItems&quot;)<br>        guard let data = try? Data(contentsOf: url) else { return nil }<br>        return try? JSONDecoder().decode([OrderDrink].self, from: data)<br>    }<br>}</pre><p>3. UploadOrder struct (本次新增)<br>上傳資料用，因為資料要上傳也要創建相對應的資料類型，才能成功上傳。</p><pre>// 上傳用的struct<br>struct UploadOrder: Codable {<br>    let records: [UploadRecord]<br>}<br><br>struct UploadRecord: Codable {<br>    let fields: UploadDrink<br>}<br><br>struct UploadDrink: Codable {<br>    var drinkName: String<br>    var capacity: String<br>    var sugar: String<br>    var ice: String<br>    var addOns: String<br>    var count: Int<br>    var totalPrice: Int<br>    var buyersName: String<br>    var imageUrl: String<br>}</pre><p>● 抓取API資料(菜單)<br>寫一個抓取資料的function，在viewDidLoad裡呼叫。</p><pre>// 接API抓取資料<br>    func fetchMenuData() {<br>        if let url = URL(string: &quot;https://api.airtable.com/v0/appazyAIzHhfRorTX/Drink&quot;) {<br>            var request = URLRequest(url: url)<br>            request.setValue(&quot;Bearer \(APIKey.default)&quot;, forHTTPHeaderField: &quot;Authorization&quot;)<br>            <br>            URLSession.shared.dataTask(with: request) { data, response, error in<br>                if let data {<br>                    let decoder = JSONDecoder()<br>                    do {<br>                        let menuResponse = try decoder.decode(Menu.self, from: data)<br>                        <br>                        // 轉換資料：因為Airtable上的makeHot我是使用Checkbox類型去存取，如果資料不是true，就不會有makeHot這個屬性，所以我將makeHot=nil的物件轉成makeHot=false；image因為是用array包著的資料，我直接將array的第0筆資料設定給tmpItem的image<br>                        let transformDrinks = menuResponse.records.map({<br>                            let tmpItem = $0.fields<br>                            return Drink(type: tmpItem.type, name: tmpItem.name, largePrice: tmpItem.largePrice, middlePrice: tmpItem.middlePrice, detail: tmpItem.detail, makeHot: tmpItem.makeHot ?? false, image: tmpItem.image[0])<br>                        })<br>                        // 將抓取的菜單設定給drinks<br>                        drinks = transformDrinks<br>                        <br>                        // 優先處理顯示畫面的動作(篩選初始要顯示的飲料、更新collectionView)<br>                        DispatchQueue.main.async {<br>                            self.filterDrinkOfType(type: .季節限定)<br>                            self.drinkCollectionView.reloadData()<br>                        }<br>                    } catch {<br>                        print(error)<br>                    }<br>                }<br>            }.resume()<br>        }<br>    }</pre><p>● 上傳訂單資料</p><pre>    // 送出訂單（上傳）<br>    @IBAction func submitTheOrder(_ sender: UIButton) {<br>        let url = URL(string: &quot;https://api.airtable.com/v0/appazyAIzHhfRorTX/Order&quot;)!<br>        var request = URLRequest(url: url)<br>        request.setValue(&quot;Bearer \(APIKey.default)&quot;, forHTTPHeaderField: &quot;Authorization&quot;)<br>        request.httpMethod = &quot;POST&quot;<br>        request.setValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>        <br>        // 資料類型轉換成UploadOrder（才可以上傳）<br>        let transformDrinks = ShoppingCart.shared.cartItems.map({<br>            UploadRecord(fields: UploadDrink(drinkName: $0.drinkName, capacity: $0.capacity, sugar: $0.sugar, ice: $0.ice, addOns: $0.addOns, count: $0.count, totalPrice: $0.totalPrice, buyersName: $0.buyersName, imageUrl: $0.imageUrl))<br>/*          保留以上簡潔的寫法<br>            let tmpItem = $0<br>            let drink = UploadDrink(drinkName: tmpItem.drinkName, capacity: tmpItem.capacity, sugar: tmpItem.sugar, ice: tmpItem.ice, addOns: tmpItem.addOns, count: tmpItem.count, totalPrice: tmpItem.totalPrice, buyersName: tmpItem.buyersName, imageUrl: tmpItem.imageUrl)<br>            let orderRecord = OrderRecord(fields: drink)<br>            return orderRecord<br> */<br>        })<br>        let uploadOrder = UploadOrder(records: transformDrinks)<br>        <br>        let encoder = JSONEncoder()<br>        let data = try? encoder.encode(uploadOrder)<br>        request.httpBody = data<br>        <br>        URLSession.shared.dataTask(with: request) { data, response, error in<br>            if let data, let content = String(data: data, encoding: .utf8) {<br>                print(content)<br>            }<br>        }.resume()<br>        <br>        // 上傳成功提示<br>        let alerController = UIAlertController(title: &quot;訂單上傳成功&quot;, message: &quot;&quot;, preferredStyle: .alert)<br>        let okAction = UIAlertAction(title: &quot;好的&quot;, style: .cancel)<br>        alerController.addAction(okAction)<br>        present(alerController, animated: true)<br>        <br>        // 清空購物車<br>        ShoppingCart.shared.cartItems.removeAll()<br>        self.orderDrinksTableView.reloadData()<br>        self.buttonIsEnable()<br>        self.calculateTotalPrice()<br>    }</pre><h3>💙 補充</h3><p>●使用Kingfisher抓圖片</p><p>1. 將套件加入專案：File → Add Package Dependencies → 搜尋Kingfisher → Add Package → Add Package</p><p>2. 先import Kingfisher</p><p>3. 在CollectionView顯示圖片，所以也在這邊抓圖，ImageView會多一個kf的屬性用來抓取url的圖片。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kxEQZCl8JUWStjgrMk8afA.png" /></figure><h3>💙 參考文章</h3><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84%E8%A9%A6%E7%85%89-%E5%8B%87%E8%80%85%E7%9A%84-100-%E9%81%93-swift-ios-app-%E8%AC%8E%E9%A1%8C/%E4%BD%A0%E5%87%BA%E5%8A%9B%E5%AF%AB-app-%E6%88%91%E5%87%BA%E9%8C%A2%E8%AB%8B%E9%A3%B2%E6%96%99-6a9ac14a2a22">#20 訂飲料 App，上傳資料到後台</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E4%B8%B2%E6%8E%A5-airtable%E7%9A%84-api-%E9%96%8B%E7%99%BC-ios-app-5e5c86c8ca7d">串接 Airtable的 API 開發 iOS App</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-run-script-%E5%92%8C-gitignore-%E7%AE%A1%E7%90%86-api-key-%E9%98%B2%E6%AD%A2%E5%AE%83%E4%B8%8A%E5%82%B3%E5%88%B0-github-c84ce81cf010">利用 Run Script 和 .gitignore 管理 API key，防止它上傳到 GitHub</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E2%91%A0%E2%91%A0%E2%91%A2-app-%E5%8F%AF%E4%BB%A5%E8%A8%82%E9%A3%B2%E6%96%99%E4%BA%86-8ac1b777b58b">①①③ App 可以訂飲料了🧋</a></li></ul><h3>💙 GitHub</h3><p><a href="https://github.com/labcgood/Kebuke">GitHub - labcgood/Kebuke</a></p><h3>💙 訂飲料App</h3><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/%E5%88%A9%E7%94%A8scrollview-stackview%E5%81%9A%E5%87%BA%E8%87%AA%E5%8B%95%E8%BC%AA%E6%92%AD%E5%BB%A3%E5%91%8A%E5%8A%9F%E8%83%BD-7c2b8db0d1e0">🍀 33 訂飲料App-利用ScrollView+StackView做出自動輪播廣告功能</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/34-%E5%88%A9%E7%94%A8collectionview%E9%A1%AF%E7%A4%BA%E9%A3%B2%E6%96%99%E9%BB%9E%E5%96%AE-4b19a5e389ad">🍀 34 訂飲料App-利用CollectionView顯示飲料點單</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/35-%E9%BB%9E%E9%A4%90%E7%95%AB%E9%9D%A2-%E5%88%A9%E7%94%A8notification%E8%AE%93textfield%E4%B8%8D%E8%A2%AB%E9%8D%B5%E7%9B%A4%E9%81%AE%E4%BD%8F-2e029670f140">🍀 35 訂飲料App-點餐畫面(利用Notification讓TextField不被鍵盤遮住)</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/36-%E8%A8%82%E9%A3%B2%E6%96%99app-%E8%B3%BC%E7%89%A9%E8%BB%8A%E5%8A%9F%E8%83%BD-90ccc510e90f">🍀 36 訂飲料App-購物車功能</a></li></ul><p>訂飲料App終於完成了｡:.ﾟヽ(*´∀`)ﾉﾟ.:｡<br>因為回了一趟老家，今天才寫完了文章，感動～<br>附上旅途中偶遇的彼得潘列車(✪ω✪)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPR41JXPPYMB44_NZxi_og.jpeg" /><figcaption>求職列車開起來！！！</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e4d95e2c17b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/37-%E8%A8%82%E9%A3%B2%E6%96%99app-%E4%B8%B2%E6%8E%A5api-0e4d95e2c17b">🧋 37 訂飲料App-串接API</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ 36 訂飲料App-購物車功能]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/36-%E8%A8%82%E9%A3%B2%E6%96%99app-%E8%B3%BC%E7%89%A9%E8%BB%8A%E5%8A%9F%E8%83%BD-90ccc510e90f?source=rss-544e92363ce9------2</link>
            <guid isPermaLink="false">https://medium.com/p/90ccc510e90f</guid>
            <dc:creator><![CDATA[Labe]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 06:34:33 GMT</pubDate>
            <atom:updated>2025-01-10T11:21:12.911Z</atom:updated>
            <content:encoded><![CDATA[<p>這次來分享購物車功能，看畫面☟</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yqyf4vRdTQ0a4JJh9oZLKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLyOfPb5N4KCX2Uip3CjuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z92CuPLRc3kNmaKacOM8kQ.png" /><figcaption>畫面</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLetC0e__iRc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLetC0e__iRc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLetC0e__iRc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4b6d61c9c7b35e816f3fd6a08e52f96/href">https://medium.com/media/f4b6d61c9c7b35e816f3fd6a08e52f96/href</a></iframe><h3>💙 步驟</h3><p>● 使用單例模式將加入購物車的資料儲存起來，讓全域使用。</p><p>● 在購物車畫面將資料顯示出來。</p><p>● 用TableView做訂單修改、刪除的功能。</p><h3>💙 Code</h3><p>● Singleton（單例設計模式）<br>創建一個ShoppingCart的Class，讓購物車清單資料可以在全域使用，不用把資料傳來傳去，方便修改訂單。</p><pre>class ShoppingCart {<br>    static let shared = ShoppingCart()<br>    <br>    private init() {<br>        cartItems = ShoppingCart.load() ?? []<br>    }<br><br>    var cartItems:[OrderDrink] = []<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWWGariGXkYQZTbjHBGYag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YAj2wPpYnx9c8dqXmdn6Dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuvP00SY7GkEFYnTx98GTA.png" /></figure><p>● 新增：<br>1.了判斷目前SegmentedControl選項位置的Code，在viewDidLoad裡使用（原本的Code就不重複放了）。<br>2.因為點餐畫面在修改點單的時候也會用到，所以我另外還有增加變數isEdit來判斷是新訂單or修改訂單，以及completeEdit的closure，用於修改訂單時把資料回傳回購物車顯示。</p><pre>    @IBAction func addToCart(_ sender: Any) {<br>        updateOrderDrinkInfo()<br>        // 判斷是否有輸入訂購人名稱，沒有輸入的話跳出通知，有輸入就先判斷是新訂單or舊訂單，儲存資料後關掉頁面<br>        // 資料會存入可以全域使用的ShoppingCart.shared.cartItems裡<br>        // 如果是修改訂單的話，會呼叫completeEdit，執行將舊資料替換掉的動作<br>        if buyersNameTextField.text == nil || buyersNameTextField.text == &quot;&quot; {<br>            showAlerController(alerTitle: &quot;請輸入訂購人名稱&quot;)<br>        } else if isEdit == false {<br>            ShoppingCart.shared.cartItems.append(orderDrink)<br>            self.dismiss(animated: true)<br>        } else if isEdit == true {<br>            completeEdit(orderDrink)<br>            self.dismiss(animated: true)<br>        }<br>    }</pre><p>● 購物車</p><pre>import UIKit<br><br>class OrderDetailViewController: UIViewController {<br><br>    @IBOutlet weak var orderDrinksTableView: UITableView!<br>    @IBOutlet weak var totalPriceLabel: UILabel!<br>    @IBOutlet weak var submitTheOrderButton: UIButton!<br>    <br>    var addDrink = OrderDrink(drinkName: &quot;&quot;, capacity: &quot;&quot;, sugar: &quot;&quot;, ice: &quot;&quot;, addOns: &quot;&quot;, count: 0, totalPrice: 0, buyersName: &quot;&quot;)<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        // Do any additional setup after loading the view.<br>        orderDrinksTableView.delegate = self<br>        orderDrinksTableView.dataSource = self<br>        <br>        submitTheOrderButton.layer.cornerRadius = 15<br>    }<br><br>    override func viewWillAppear(_ animated: Bool) {<br>        // 更新畫面<br>        orderDrinksTableView.reloadData()<br>        buttonIsEnable()<br>        // 計算總金額並顯示<br>        calculateTotalPrice()<br>    }<br>    <br>    // 計算總金額<br>    func calculateTotalPrice() {<br>        let totalPrice = ShoppingCart.shared.cartItems.reduce(0) { $0 + $1.totalPrice }<br>        totalPriceLabel.text = &quot;＄\(totalPrice)&quot;<br>    }<br>    <br>    // 判斷是否可使用送出訂單的Button<br>    func buttonIsEnable() {<br>        if ShoppingCart.shared.cartItems.isEmpty == true {<br>            submitTheOrderButton.isEnabled = false<br>        } else {<br>            submitTheOrderButton.isEnabled = true<br>        }<br>    }<br>    <br>    // 修改訂單<br>    @IBSegueAction func toOrderVC(_ coder: NSCoder, sender: Any?, segueIdentifier: String?) -&gt; OrderViewController? {<br>        // 取得選取Cell的Row，把相應位置的資料傳給編輯頁面，isEdit設定成true（讓頁面知道這是修改訂單而不是新訂單），修改完成時在按下Button時會呼叫completeEdit，執行這邊寫的Code<br>        guard let row = orderDrinksTableView.indexPathForSelectedRow?.row else { return nil }<br>        let controll = OrderViewController(coder: coder)<br>        controll?.orderDrink = ShoppingCart.shared.cartItems[row]<br>        controll?.isEdit = true<br>        controll?.completeEdit = { drink in<br>            ShoppingCart.shared.cartItems[row] = drink<br>            self.orderDrinksTableView.reloadData()<br>            self.calculateTotalPrice()<br>        }<br>        return controll<br>    }<br>}<br><br>extension OrderDetailViewController: UITableViewDelegate, UITableViewDataSource {<br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        ShoppingCart.shared.cartItems.count<br>    }<br>    <br>    // 顯示Cell<br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        guard let cell = tableView.dequeueReusableCell(withIdentifier: OrderDrinksTableViewCell.reuseIdentifier, for: indexPath) as? OrderDrinksTableViewCell else { fatalError() }<br>        cell.drinkImageView.image = UIImage(named: ShoppingCart.shared.cartItems[indexPath.row].drinkName)<br>        cell.nameSizeAndCountLabel.text = &quot;\(ShoppingCart.shared.cartItems[indexPath.row].drinkName)/\(ShoppingCart.shared.cartItems[indexPath.row].capacity)*\(ShoppingCart.shared.cartItems[indexPath.row].count)杯&quot;<br>        cell.sugarAndIceLabel.text = &quot;糖量：\(ShoppingCart.shared.cartItems[indexPath.row].sugar)/冰量：\(ShoppingCart.shared.cartItems[indexPath.row].ice)&quot;<br>        cell.addOnsLabel.text = &quot;加料：\(ShoppingCart.shared.cartItems[indexPath.row].addOns)&quot;<br>        cell.buyersNameLabel.text = &quot;訂購人：\(ShoppingCart.shared.cartItems[indexPath.row].buyersName)&quot;<br>        cell.priceLabel.text = &quot;金額：\(ShoppingCart.shared.cartItems[indexPath.row].totalPrice)元&quot;<br>        return cell<br>    }<br>    <br>    // 刪除訂單<br>    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {<br>        if editingStyle == .delete {<br>            ShoppingCart.shared.cartItems.remove(at: indexPath.row)<br>            tableView.deleteRows(at: [indexPath], with: .automatic)<br>            self.calculateTotalPrice()<br>            buttonIsEnable()<br>        }<br>    }<br>}</pre><p>● 購物車的Cell</p><pre>import UIKit<br><br>class OrderDrinksTableViewCell: UITableViewCell {<br>    static let reuseIdentifier = &quot;\(OrderDrinksTableViewCell.self)&quot;<br>    <br>    @IBOutlet weak var drinkImageView: UIImageView!<br>    @IBOutlet weak var nameSizeAndCountLabel: UILabel!<br>    @IBOutlet weak var sugarAndIceLabel: UILabel!<br>    @IBOutlet weak var addOnsLabel: UILabel!<br>    @IBOutlet weak var buyersNameLabel: UILabel!<br>    @IBOutlet weak var priceLabel: UILabel!<br>    @IBOutlet weak var view: UIView!<br>    <br>    <br>    override func awakeFromNib() {<br>        super.awakeFromNib()<br>        // Initialization code<br>        <br>        drinkImageView.layer.cornerRadius = 13<br>        // 利用View做出row的間距<br>        view.backgroundColor = .white<br>        view.layer.cornerRadius = 15<br>    }<br><br>    override func setSelected(_ selected: Bool, animated: Bool) {<br>        super.setSelected(selected, animated: animated)<br>        // Configure the view for the selected state<br>    }<br>}</pre><h3>💙 補充</h3><p>利用View做出Row的間距的間距，讓Cell有像TableView Section的Inset Grouped外觀：</p><p>在Cell裡加入一個View，再把其他元件包在裡面，使用AutoLayout讓View跟上下左右都設定自己想要的距離，就可以做出這樣的效果啦～<br>之前在做第二個ToDoList的App時，因為想要做這種效果，所以使用了Section，然後就遇到了很多困難，因為很多功能要直接使用Row比較方便😣這次學會了這個方法又更上一層樓啦🥳</p><h3>💙 GitHub</h3><p><a href="https://github.com/labcgood/Kebuke">GitHub - labcgood/Kebuke</a></p><p>(ﾉ◕ヮ◕)ﾉ*:･ﾟ✧</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90ccc510e90f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/36-%E8%A8%82%E9%A3%B2%E6%96%99app-%E8%B3%BC%E7%89%A9%E8%BB%8A%E5%8A%9F%E8%83%BD-90ccc510e90f">🧋 36 訂飲料App-購物車功能</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ 35 訂飲料App-點餐畫面(利用Notification讓TextField不被鍵盤遮住)]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/35-%E9%BB%9E%E9%A4%90%E7%95%AB%E9%9D%A2-%E5%88%A9%E7%94%A8notification%E8%AE%93textfield%E4%B8%8D%E8%A2%AB%E9%8D%B5%E7%9B%A4%E9%81%AE%E4%BD%8F-2e029670f140?source=rss-544e92363ce9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e029670f140</guid>
            <dc:creator><![CDATA[Labe]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 07:17:32 GMT</pubDate>
            <atom:updated>2025-01-10T11:20:52.727Z</atom:updated>
            <content:encoded><![CDATA[<p>原本點餐畫面應該會簡簡單單的帶過，但在執行App過程中TextField被鍵盤擋住的畫面實在太令人受不了，所以決定還是研究、處理一下😵‍💫<br>一樣先看看畫面吧☟</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJlnix3rO8mWMYpYBomBxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RljyTx9S-wBQnfVx8Y_eww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJCJM5LHEH6WgyirseTMfQ.png" /><figcaption>畫面</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMsyLYPG4cPg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FMsyLYPG4cPg%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMsyLYPG4cPg%2Fhq2.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/54305650f3557440c4e0b906558c3726/href">https://medium.com/media/54305650f3557440c4e0b906558c3726/href</a></iframe><h3>💙 步驟</h3><p>● 利用IBSegueAction將選取的飲料資料傳到點餐畫面並顯示出來。</p><p>● 使用SegmentedControl來選取餐點內容、Button選擇杯數。</p><p>● TextField輸入訂購人名稱。</p><p>● 用Notification做法讓鍵盤呼叫出來不要擋住TextField，不然使用者會看不到自己打了什麼字。</p><h3>💙 Code</h3><p>● 在Drink資料夾裡多建立一個用來存取所點飲料資料的struct，以及用來判斷所選SegmentedControl的enum（增加可讀性）</p><pre>// 用於點選飲料及購物車頁面<br>struct OrderDrink {<br>    var drinkName: String<br>    var capacity: String<br>    var sugar: String<br>    var ice: String<br>    var addOns: String<br>    var count: Int<br>    var totalPrice: Int<br>    var buyersName: String<br>}<br><br>enum DrinkContentOption:Int {<br>    case 容量, 糖量, 冰量, 加料<br>}</pre><p>● IBSegueAction（寫在HomeViewController）</p><pre>    @IBSegueAction func toOrderViewController(_ coder: NSCoder) -&gt; OrderViewController? {<br>        let controller = OrderViewController(coder: coder)<br>        guard let index = self.drinkCollectionView.indexPathsForSelectedItems?.first?.item else { return nil }<br>        controller?.currentShowDrink = selectDrinks[index]<br>        return controller<br>    }</pre><p>● 點餐內容</p><pre>import UIKit<br><br>class OrderViewController: UIViewController {<br>    <br>    @IBOutlet weak var drinkImageView: UIImageView!<br>    @IBOutlet weak var drinkNameLabel: UILabel!<br>    @IBOutlet weak var drinkDetailLabel: UILabel!<br>    @IBOutlet weak var orderCountLabel: UILabel!<br>    @IBOutlet weak var buyersNameTextField: UITextField!<br>    <br>    // 判斷溫、熱飲不能加菓玉用<br>    @IBOutlet weak var iceSegmentedControl: UISegmentedControl!<br>    @IBOutlet weak var addOnsSegmentedControl: UISegmentedControl!<br>    var iceSelectIndex = 0<br>    var addOnsSelectIndex = 3<br>    <br>    // 存取顯示飲料、所點飲料內容資料<br>    var currentShowDrink = Drink(type: .單品茶, name: &quot;&quot;, largePrice: 0, middlePrice: 0, detail: &quot;&quot;, makeHot: true)<br>    var orderDrink = OrderDrink(drinkName: &quot;&quot;, capacity: &quot;大杯&quot;, sugar: &quot;正常&quot;, ice: &quot;正常&quot;, addOns: &quot;無&quot;, count: 1, totalPrice: 0, buyersName: &quot;&quot;)<br><br><br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        print(currentShowDrink)<br>        // Do any additional setup after loading the view.<br>        buyersNameTextField.delegate = self<br>        <br>        // 顯示目前飲料資訊<br>        // 在寫這次點餐的過程中才想到需要判斷一些溫、熱飲的條件，所以在原本的Drink的struct中有再多加入屬性makeHot來判斷是否可以做熱飲，並在顯示飲料名稱時，可以做熱飲的名稱後面多加了Ⓗ<br>        drinkImageView.image = UIImage(named: currentShowDrink.name)<br>        if currentShowDrink.makeHot == true {<br>            drinkNameLabel.text = currentShowDrink.name + &quot;Ⓗ&quot;<br>        } else {<br>            drinkNameLabel.text = currentShowDrink.name<br>        }<br>        drinkDetailLabel.text = currentShowDrink.detail<br><br>        // 鍵盤不擋住TextField的方法<br>        setKeyboardNotification()<br>    }<br>    <br>    <br>    // 將SegmentedControl選擇的選項文字設定給orderDrink<br>    // 有些飲品不做溫、熱飲，所以在冰量欄位會做判斷<br>    // 在冰量及加料欄位需判斷菓玉不得做溫、熱飲<br>    // 記下原本選項的index，讓SegmentedControl選項可以維持在原來的選擇<br>    @IBAction func selecDrinkContent(_ sender: UISegmentedControl) {<br>        let option = DrinkContentOption(rawValue: sender.tag)<br>        switch option {<br>        case .容量:<br>            orderDrink.capacity = sender.titleForSegment(at: sender.selectedSegmentIndex)!<br>        case .糖量:<br>            orderDrink.sugar = sender.titleForSegment(at: sender.selectedSegmentIndex)!<br>        case .冰量:<br>            // 判斷不可做熱飲<br>            if (currentShowDrink.makeHot == false &amp;&amp; sender.selectedSegmentIndex == 6) || (currentShowDrink.makeHot == false &amp;&amp; sender.selectedSegmentIndex == 7) {<br>                showAlerController(alerTitle: &quot;不可做溫、熱飲&quot;)<br>                sender.selectedSegmentIndex = iceSelectIndex<br>            }<br>            // 菓玉<br>            if (addOnsSegmentedControl.selectedSegmentIndex == 2 &amp;&amp; sender.selectedSegmentIndex == 6) || (addOnsSegmentedControl.selectedSegmentIndex == 2 &amp;&amp; sender.selectedSegmentIndex == 7) {<br>                showAlerController(alerTitle: &quot;溫、熱飲不得加菓玉&quot;)<br>                sender.selectedSegmentIndex = iceSelectIndex<br>            } else {<br>                iceSelectIndex = sender.selectedSegmentIndex<br>            }<br>            orderDrink.ice = sender.titleForSegment(at: sender.selectedSegmentIndex)!<br>        case .加料:<br>            if (iceSegmentedControl.selectedSegmentIndex == 6 &amp;&amp; sender.selectedSegmentIndex == 2) || (iceSegmentedControl.selectedSegmentIndex == 7 &amp;&amp; sender.selectedSegmentIndex == 2) {<br>                showAlerController(alerTitle: &quot;溫、熱飲不得加菓玉&quot;)<br>                sender.selectedSegmentIndex = addOnsSelectIndex<br>                print(sender.selectedSegmentIndex)<br>            } else {<br>                addOnsSelectIndex = sender.selectedSegmentIndex<br>            }<br>            orderDrink.addOns = sender.titleForSegment(at: sender.selectedSegmentIndex)!<br>        default:<br>            break<br>        }<br>    }<br>    <br>    // 跳出提醒（因為多個地方都會用到，所以獨立寫出一個function，方便使用）<br>    func showAlerController(alerTitle: String) {<br>        let alerController = UIAlertController(title: alerTitle, message: nil, preferredStyle: .alert)<br>        let okAction = UIAlertAction(title: &quot;好的&quot;, style: .cancel)<br>        alerController.addAction(okAction)<br>        present(alerController, animated: true)<br>    }<br>    <br>    // 杯數<br>    @IBAction func orderCount(_ sender: UIButton) {<br>        let option = sender.tag<br>        switch option {<br>        case 0:<br>            if orderDrink.count &gt; 1 {<br>                orderDrink.count -= 1<br>            }<br>            orderCountLabel.text = &quot;\(orderDrink.count)&quot;<br>        case 1:<br>            orderDrink.count += 1<br>            orderCountLabel.text = &quot;\(orderDrink.count)&quot;<br>        default:<br>            break<br>        }<br>    }<br>    <br>    // 存取飲料的其他資訊<br>    func updateOrderDrinkInfo() {<br>        // 存取飲品名稱<br>        orderDrink.drinkName = currentShowDrink.name<br>        // 存取訂購人名稱<br>        if let name = buyersNameTextField.text {<br>            orderDrink.buyersName = name<br>        }<br>        // 存取總金額<br>        if orderDrink.capacity == &quot;大杯&quot; {<br>            orderDrink.totalPrice += currentShowDrink.largePrice * orderDrink.count<br>        } else if orderDrink.capacity == &quot;中杯&quot; {<br>            orderDrink.totalPrice += currentShowDrink.middlePrice * orderDrink.count<br>        }<br>        if orderDrink.addOns != &quot;無&quot; {<br>            orderDrink.totalPrice += 10 * orderDrink.count<br>        }<br>    }<br>    <br>    // 加入購物車<br>    @IBAction func addToCart(_ sender: Any) {<br>        updateOrderDrinkInfo()<br>        // 判斷是否有輸入訂購人名稱，沒有輸入的話跳出通知，有輸入就關掉頁面（之後會再加把資料傳到購物車的功能）<br>        if buyersNameTextField.text == nil || buyersNameTextField.text == &quot;&quot; {<br>            showAlerController(alerTitle: &quot;請輸入訂購人名稱&quot;)<br>        } else {<br>            self.dismiss(animated: true)<br>        }<br>    }<br>}</pre><p>● 鍵盤（參考文章講解得很詳細，真的非常感謝這位大大👍）</p><pre>// TextField設定：收鍵盤、打字時移動View不擋住TextField<br>extension OrderViewController: UITextFieldDelegate {<br>    <br>    // 點選return收回鍵盤<br>    func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool {<br>            textField.resignFirstResponder()<br>            return true<br>    }<br>    <br>    // 根據鍵盤的顯示、收起的動作來決定移動View<br>    func setKeyboardNotification() {<br>        let center:NotificationCenter = NotificationCenter.default<br>        center.addObserver(self, selector: #selector(keyboardShown), name: UIResponder.keyboardWillShowNotification, object: nil)<br>        center.addObserver(self, selector: #selector(keyboardHidden), name: UIResponder.keyboardWillHideNotification, object: nil)<br>    }<br>    <br>    // 將View上移<br>    @objc func keyboardShown(notification: Notification) {<br>        // 取得鍵盤尺寸<br>        let info: NSDictionary = notification.userInfo! as NSDictionary<br>        let keyboardSize = (info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue<br>        <br>        // 計算鍵盤頂部的y座標、TextField底部的y座標，相減得到兩者距離（且如果數字大於0，就表示有被擋住，小於0則否）<br>        let keyboardTopY = self.view.frame.height - keyboardSize.height<br>        let buyersNameTextFieldBottomY = self.buyersNameTextField.convert(buyersNameTextField.bounds, to: self.view).maxY<br>        let targetY = Int(buyersNameTextFieldBottomY - keyboardTopY)<br>        <br>        // 判斷如果有被遮住就移動（View要往上移，y軸就要是負數）<br>        // 除了鍵盤移動的距離，這邊多加了80是因為鍵盤上會有預設輸入選項，這也會擋到TextField，所以我自己測試後決定多+80<br>        if self.view.frame.minY &gt;= 0 {<br>            if targetY &gt; 0 {<br>                UIView.animate(withDuration: 0.25) {<br>                    self.view.frame = CGRect(x: 0, y: -(targetY + 80), width: Int(self.view.frame.width), height: Int(self.view.frame.height))<br>                }<br>            }<br>        }<br>    }<br>    <br>    // 將View移動回來<br>    @objc func keyboardHidden(notification: Notification) {<br>        UIView.animate(withDuration: 0.25) {<br>            self.view.frame = CGRect(x: 0, y: 0, width: Int(self.view.frame.width), height: Int(self.view.frame.height))<br>        }<br>    }<br>}</pre><h3>💙 參考文章</h3><p>要讓TextField不要被鍵盤擋住有幾種方法，我目前知道的有：<br>1. 直接使用TableView做畫面：當使用TableView搭配TextField時，如果被擋住，畫面會自動上移，非常方便🥺。<br>2. 跟本篇文章一樣使用Notification。<br>3. 使用ScrollView：這似乎會比Notification更方便一些，我因為已經做好畫面才想到要加入這個功能，所以直接用Notification的方法😳下面也放了一篇文章，是講解ScrollView的做法，未來也用到就可以參考啦，真的感謝每個寫文章的大大們！</p><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E6%95%99%E5%AE%A4/4-xcode-%E4%BD%95%E4%B8%8D%E5%A4%A7%E6%96%B9%E6%8A%8Atextfield%E6%94%BE%E4%B8%8B%E9%9D%A2-7a0c135f3cd">#4 Xcode-鍵盤擋住textfield該怎麼辦?</a></li><li><a href="https://ithelp.ithome.com.tw/articles/10227750">D28 - 你的輸入，我看得見 - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-contentinset-%E8%AE%93%E9%8D%B5%E7%9B%A4%E5%87%BA%E7%8F%BE%E6%99%82-scroll-view-%E8%87%AA%E5%8B%95%E4%B8%8A%E7%A7%BB-687ab82990f7">利用 contentInset 讓鍵盤出現時 scroll view 自動上移</a></li></ul><h3>💙 GitHub</h3><p><a href="https://github.com/labcgood/Kebuke">GitHub - labcgood/Kebuke</a></p><p>下次要做完這個App了🫠<br>接著再來串API，進度快一點啊啊啊啊啊😧</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e029670f140" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/35-%E9%BB%9E%E9%A4%90%E7%95%AB%E9%9D%A2-%E5%88%A9%E7%94%A8notification%E8%AE%93textfield%E4%B8%8D%E8%A2%AB%E9%8D%B5%E7%9B%A4%E9%81%AE%E4%BD%8F-2e029670f140">🧋 35 訂飲料App-點餐畫面(利用Notification讓TextField不被鍵盤遮住)</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ 34 訂飲料App-利用CollectionView顯示飲料點單]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/34-%E5%88%A9%E7%94%A8collectionview%E9%A1%AF%E7%A4%BA%E9%A3%B2%E6%96%99%E9%BB%9E%E5%96%AE-4b19a5e389ad?source=rss-544e92363ce9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b19a5e389ad</guid>
            <dc:creator><![CDATA[Labe]]></dc:creator>
            <pubDate>Tue, 30 Jul 2024 05:39:59 GMT</pubDate>
            <atom:updated>2025-01-10T11:20:31.183Z</atom:updated>
            <content:encoded><![CDATA[<p>如標題，這次在訂飲料App中增加了顯示飲料品項用的CollectionView，並藉由Button來切換顯示不同種類的飲料，先看成果☟</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdBOzbeDEnpFd4vD5FF_Jg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IXn-RkBrVaAhPlFQHaRJ_w.png" /><figcaption>畫面</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6p5jUEKCIVk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2F6p5jUEKCIVk%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6p5jUEKCIVk%2Fhq2.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc89f7b9d522efcdffb268b54304f825/href">https://medium.com/media/cc89f7b9d522efcdffb268b54304f825/href</a></iframe><h3>💙 步驟</h3><p>● 建立Drink的Struct，把飲料的資料建立起來。</p><p>● 利用ScrollView+StackView+Button把飲料的種類列出來。</p><p>● CollectionView顯示目前選擇種類的飲料</p><h3>💙 Code</h3><p>● Drink<br>這邊只有單品茶全部放上來，其他種類就各放2個當範例～</p><pre>struct Drink {<br>    let type: Type<br>    let name: String<br>    let largePrice: Int<br>    let middlePrice: Int<br>}<br><br>// 生成Drink時，方便輸入及減少打字錯誤<br>enum Type:String {<br>    case 季節限定, 單品茶, 調茶, 雲蓋, 歐蕾<br>}<br><br>// 用於選取Button時的判斷（增加可讀性）<br>enum DrinkOption:Int {<br>    case 季節限定, 單品茶, 調茶, 雲蓋, 歐蕾<br>}<br><br>let drinks:[Drink] = [<br>    Drink(type: .季節限定, name: &quot;金蘋春芽&quot;, largePrice: 70, middlePrice: 60),<br>    Drink(type: .單品茶, name: &quot;熟成紅茶&quot;, largePrice: 40, middlePrice: 35),<br>    Drink(type: .單品茶, name: &quot;麗春紅茶&quot;, largePrice: 40, middlePrice: 35),<br>    Drink(type: .單品茶, name: &quot;胭脂紅茶&quot;, largePrice: 50, middlePrice: 45),<br>    Drink(type: .單品茶, name: &quot;金蜜紅茶&quot;, largePrice: 50, middlePrice: 60),<br>    Drink(type: .單品茶, name: &quot;春芽綠茶&quot;, largePrice: 40, middlePrice: 35),<br>    Drink(type: .單品茶, name: &quot;雪花冷露&quot;, largePrice: 40, middlePrice: 35),<br>    Drink(type: .單品茶, name: &quot;熟成冷露&quot;, largePrice: 40, middlePrice: 35),<br>    Drink(type: .單品茶, name: &quot;春芽冷露&quot;, largePrice: 40, middlePrice: 35),<br>    Drink(type: .調茶, name: &quot;熟成檸果&quot;, largePrice: 70, middlePrice: 60),<br>    Drink(type: .調茶, name: &quot;冷露檸果&quot;, largePrice: 70, middlePrice: 60),<br>    Drink(type: .雲蓋, name: &quot;雲蓋熟成&quot;, largePrice: 65, middlePrice: 60),<br>    Drink(type: .雲蓋, name: &quot;雲蓋麗春&quot;, largePrice: 65, middlePrice: 60),<br>    Drink(type: .歐蕾, name: &quot;熟成歐蕾&quot;, largePrice: 65, middlePrice: 55),<br>    Drink(type: .歐蕾, name: &quot;冷露歐蕾&quot;, largePrice: 65, middlePrice: 55)<br>]</pre><p>● 顯示飲料（有拿掉之前放過的code，如果要看完整的code可以在GitHub下載呦）</p><pre>class HomeViewController: UIViewController {<br><br>    @IBOutlet weak var drinkCollectionView: UICollectionView!<br>    @IBOutlet var drinkTypeButtons: [UIButton]!<br>    <br>    var selectDrinks:[Drink] = [] //分類後要顯示的飲料<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        // Do any additional setup after loading the view.<br><br>        // 設定HomeViewController是drinkCollectionView的delegate跟dataSource<br>        // 設定Button圓角<br>        drinkCollectionView.delegate = self<br>        drinkCollectionView.dataSource = self<br>        for i in 0...drinkTypeButtons.count-1 {<br>            drinkTypeButtons[i].layer.cornerRadius = 17<br>        }<br>        <br>        // 初始要顯示的飲料<br>        filterDrinkOfType(type: .季節限定)<br>        self.drinkCollectionView.reloadData()<br>    }<br>    <br>    // 判斷目前選取的飲料種類<br>    @IBAction func selectDrinkType(_ sender: UIButton) {<br>        let option = DrinkOption(rawValue: sender.tag)<br>        switch option {<br>        case .季節限定:<br>            filterDrinkOfType(type: .季節限定)<br>        case .單品茶:<br>            filterDrinkOfType(type: .單品茶)<br>        case .調茶:<br>            filterDrinkOfType(type: .調茶)<br>        case .雲蓋:<br>            filterDrinkOfType(type: .雲蓋)<br>        case .歐蕾:<br>            filterDrinkOfType(type: .歐蕾)<br>        default:<br>            break<br>        }<br>        self.drinkCollectionView.reloadData()<br>    }<br>    <br>    // 篩選各種類的飲料，設定給selectDrinks，讓CollectionView顯示出來<br>    func filterDrinkOfType(type: Type) {<br>        let currentDrinkType = drinks.filter { $0.type == type }<br>        selectDrinks = currentDrinkType<br>    }<br><br>}<br><br>// 擴展HomeViewController，遵循UICollectionViewDelegate、UICollectionViewDataSource，顯示我們的飲料<br>extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource {<br>    <br>    // 設定item的數量<br>    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>        selectDrinks.count<br>    }<br>    <br>    // 設定cell要顯示的內容<br>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DrinkCollectionViewCell.reuseIdentifier, for: indexPath) as! DrinkCollectionViewCell<br>        let image = UIImage(named: selectDrinks[indexPath.item].name)<br>        cell.drinkImageView.image = image<br>        cell.drinkNameLabel.text = selectDrinks[indexPath.item].name<br>        cell.drinkPriceLabel.text = &quot;中:\(selectDrinks[indexPath.item].middlePrice)／大:\(selectDrinks[indexPath.item].largePrice)&quot;<br>        setupCellSize()<br>        return cell<br>    }<br>    <br>    // 設定cell的大小<br>    func setupCellSize() {<br>        let itemSpace: Double = 0<br>        let columCount: Double = 2<br>        // 為了使用flowLayout屬性(用來排版、控制cell大小)，所以我們這邊進行轉型。<br>        let flowLayout = self.drinkCollectionView.collectionViewLayout as? UICollectionViewFlowLayout<br>        <br>        // cell大小<br>        let width = floor((self.drinkCollectionView.bounds.width - itemSpace * (columCount-1)) / columCount)<br>        flowLayout?.itemSize = CGSize(width: width, height: width)<br>        // 將預設尺寸設為0，讓CollectionViewCell不會用AutoLayout去算尺寸，或在StoryBoard把CollectionViewCell的EstimateSize設定成None也可以<br>        flowLayout?.estimatedItemSize = .zero<br>        // 間距設定<br>        flowLayout?.minimumLineSpacing = itemSpace<br>        flowLayout?.minimumInteritemSpacing = itemSpace<br>    }<br>    <br>}</pre><p>● cell</p><pre>class DrinkCollectionViewCell: UICollectionViewCell {<br>    <br>    // 在設定cell要顯示的內容時，我們會用到轉型，在轉型時會需要輸入cell的id，為了預防我們打錯字或是增加程式可讀性，我們在這邊定義reuseIdentifier屬性，在使用時可以用DrinkCollectionViewCell.reuseIdentifier來呼叫<br>    static let reuseIdentifier = &quot;\(DrinkCollectionViewCell.self)&quot;<br>    <br>    @IBOutlet weak var drinkImageView: UIImageView!<br>    @IBOutlet weak var drinkNameLabel: UILabel!<br>    @IBOutlet weak var drinkPriceLabel: UILabel!<br><br>}</pre><p>● 補充</p><p>這次加上了CollectionView後執行發現了問題，在CollectionView滑動時，上次完成的廣告輪播功能會停止，如下附影片☟</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXtg18tiiU6Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FXtg18tiiU6Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXtg18tiiU6Y%2Fhq2.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/654c48aa25dab479584fbce702f73dfa/href">https://medium.com/media/654c48aa25dab479584fbce702f73dfa/href</a></iframe><p>詢問彼得後主要有2個問題：</p><p>1. RunLoop<br>滑動的手勢會影響Timer，造成Timer停止的問題。<br>解決方法：加上RunLoop.current.add(self.bannerTimer!, forMode: .common)</p><pre>    func setupTimer() {<br>        stopTimer() // 確保生成Timer前，消除已存在的Timer，以免重複存在<br>        <br>        self.bannerTimer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { timer in<br>            if (self.adImages.count &gt; 1) {<br>                let index = (self.adPageControl.currentPage + 1) % (self.adImages.count + 1)<br>                self.adScrollView.setContentOffset(CGPoint(x: CGFloat(index + 1) * self.view.frame.width, y: 0), animated: true)<br>            } else {<br>                self.stopTimer()<br>            }<br>        })<br>        RunLoop.current.add(self.bannerTimer!, forMode: .common)<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C8xeDt2KW8mZwUECl6kRuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nl0aAR8qHlwJvnfRZ5-nIQ.png" /></figure><p><a href="https://ithelp.ithome.com.tw/articles/10305916?sc=iThelpR">[鐵人賽 Day 26] Swift 仿刻 IOS 內建的 Clock - 馬錶 (2) 主要程式碼內容介紹 - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></p><p>2. 判斷正在滑動的ScrollView是哪個<br>在使用ScrollView的各種滑動情形來控制Timer及頁面轉跳時，前面先用if scrollView == adScrollView來判斷滑動的是adScrollView。</p><pre>extension HomeViewController: UIScrollViewDelegate {<br>    <br>    // scrollView開始滑動時，消除Timer<br>    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {<br>        if scrollView == adScrollView {<br>            if adImages.count &gt; 0 {<br>                stopTimer()<br>            }<br>        }<br>    }<br>    <br>    // scrollView停止滑動時，生成Timer，開始輪播<br>    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer&lt;CGPoint&gt;) {<br>        if scrollView == adScrollView {<br>            if adImages.count &gt; 0 {<br>                setupTimer()<br>            }<br>        }<br>    }<br>    <br>    // scrollView內容發生滾動時，無限輪播、PageControl轉跳<br>    func scrollViewDidScroll(_ scrollView: UIScrollView) {<br>        if scrollView == adScrollView {<br>            let currentX = adScrollView.contentOffset.x<br>            if currentX == 0 {<br>                let lastAdContentOffsetX = scrollView.frame.width * CGFloat(adImages.count)<br>                adScrollView.contentOffset = CGPoint(x: lastAdContentOffsetX, y: 0)<br>            } else if currentX == scrollView.frame.width * CGFloat(adImages.count + 1) {<br>                adScrollView.contentOffset = CGPoint(x: scrollView.frame.width, y: 0)<br>            }<br>            <br>            if scrollView == self.adScrollView {<br>                let page = round(scrollView.contentOffset.x / scrollView.frame.width) - 1<br>                self.adPageControl.currentPage = Int(page)<br>            }<br>        }<br>    }<br>}</pre><h3>💙 參考文章</h3><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%88%A9%E7%94%A8-flow-layout-%E7%9A%84-collection-view-%E8%A3%BD%E4%BD%9C%E7%85%A7%E7%89%87%E7%89%86-e31dad55a7ac">利用 flow layout 的 collection view 製作照片牆</a></p><h3>💙 GitHub</h3><p><a href="https://github.com/labcgood/Kebuke">GitHub - labcgood/Kebuke</a></p><p>下一篇文章應該會是做加入購物車的功能(*´ω`)人(´ω`*)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b19a5e389ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/34-%E5%88%A9%E7%94%A8collectionview%E9%A1%AF%E7%A4%BA%E9%A3%B2%E6%96%99%E9%BB%9E%E5%96%AE-4b19a5e389ad">🧋 34 訂飲料App-利用CollectionView顯示飲料點單</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ 33 訂飲料App-利用ScrollView+StackView做出自動輪播廣告功能]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8scrollview-stackview%E5%81%9A%E5%87%BA%E8%87%AA%E5%8B%95%E8%BC%AA%E6%92%AD%E5%BB%A3%E5%91%8A%E5%8A%9F%E8%83%BD-7c2b8db0d1e0?source=rss-544e92363ce9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c2b8db0d1e0</guid>
            <dc:creator><![CDATA[Labe]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 08:37:12 GMT</pubDate>
            <atom:updated>2025-01-10T11:20:14.766Z</atom:updated>
            <content:encoded><![CDATA[<p>除了複習之前的課程，跟做一些小練習，現在也要一步一步把訂飲料App寫一寫，這次先來做首頁的廣告輪播功能☟</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYVe-_wo9UYg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FYVe-_wo9UYg%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYVe-_wo9UYg%2Fhq2.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4de5b6813907034e843f9aa7992494af/href">https://medium.com/media/4de5b6813907034e843f9aa7992494af/href</a></iframe><h3>💙 步驟</h3><p>● 在Storyboard加入ScrollView，ScrollView裡再加入StackView，StackView裡面放ImageView。</p><p>● 調整AutoLayout<br>1. ScrollView：<br>X軸置中、與Safe Area首尾及頂部對齊、底部與其他元件相連(依畫面設計）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*8wXgNWr5aHBQE7Sy_zbzwQ.png" /></figure><p>2. StackView：<br>四邊與ScrollView的Content Layout Guide對齊。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*tgkx_Vh79zui495EfS2xLA.png" /></figure><p>3. ImageView：<br>寬高與ScrollView的Frame Layout Guide對齊。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*wVPfjyzoSkpMdBlK0hd49A.png" /></figure><p>4. 如果有使用Page Controll就再多做設定。</p><p>● 打開ScrollView的Paging Enabled，讓頁面有一頁一頁的效果。</p><p>● 用程式來加入廣告的圖片。</p><p>● 使用Timer搭配ScrollView的ContentOffset來讓廣告無限自動輪播。<br>這地方比較特別的是我在放廣告時，前後會個多加一個廣告，如下圖☟</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4hemTLy51kuCZBaztYNSA.png" /></figure><p>當廣告滑到右邊的ad1時，使用ScrollView的ContentOffset讓ScrollView自己滑回左邊的ad1，讓廣告有無限循環的效果（ad5同理）。</p><h3>💙 Code</h3><pre>import UIKit<br><br>class HomeViewController: UIViewController {<br><br>    @IBOutlet weak var adScrollView: UIScrollView!<br>    @IBOutlet weak var adStackView: UIStackView!<br>    @IBOutlet weak var adImageView: UIImageView!<br>    @IBOutlet weak var adPageControl: UIPageControl!<br>    @IBOutlet weak var drinkCollectionView: UICollectionView!<br>    <br>    var adImages = [&quot;ad1&quot;, &quot;ad2&quot;, &quot;ad3&quot;, &quot;ad4&quot;, &quot;ad5&quot;] // 建立廣告圖片名稱的Array<br>    var bannerTimer: Timer?<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        // Do any additional setup after loading the view.<br>        adScrollView.delegate = self<br>        <br>        setupAdPageControl()<br>        addAd(imageNameArray: adImages)<br>        setupTimer()<br>    }<br>    <br>    //  設定PageControl<br>    func setupAdPageControl() {<br>        adPageControl.numberOfPages = adImages.count<br>        adPageControl.pageIndicatorTintColor = .white<br>        adPageControl.currentPageIndicatorTintColor = .gray<br>        adPageControl.currentPage = 0<br>    }<br>    <br>    // 設定、加入廣告到ScrollView<br>    func addAd(imageNameArray: [String]) {<br>        // 初始顯示位置<br>        adScrollView.contentOffset = CGPoint(x: view.frame.width, y: 0)<br>        // 加入廣告圖片<br>        adImageView.image = UIImage(named: imageNameArray[imageNameArray.count-1])<br>        for i in 0...imageNameArray.count-1 {<br>            let imageView = UIImageView(image: UIImage(named: imageNameArray[i]))<br>            imageView.contentMode = .scaleAspectFit<br>            adStackView.addArrangedSubview(imageView)<br>        }<br>        let firstAdImageView = UIImageView(image: UIImage(named: imageNameArray[0]))<br>        firstAdImageView.contentMode = .scaleAspectFit<br>        adStackView.addArrangedSubview(firstAdImageView)<br>    }<br>    <br>    // 設定Timer 3秒切換一次廣告<br>    func setupTimer() {<br>        stopTimer() // 確保生成Timer前，消除已存在的Timer，以免重複存在<br>        <br>        self.bannerTimer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: { timer in<br>            if (self.adImages.count &gt; 1) {<br>                let index = (self.adPageControl.currentPage + 1) % (self.adImages.count + 1)<br>                self.adScrollView.setContentOffset(CGPoint(x: CGFloat(index + 1) * self.view.frame.width, y: 0), animated: true)<br>            } else {<br>                self.stopTimer()<br>            }<br>        })<br>}    <br><br>    // 消除已存在的Timer<br>    func stopTimer() {<br>        if bannerTimer != nil {<br>            bannerTimer?.invalidate()<br>        }<br>    }<br>}<br><br><br>// 擴展HomeViewController，遵循UIScrollViewDelegate來控制滑動廣告時Timer的變化(滑動時應該停止，放開時再次啟動)，以及無限輪播效果(上文步驟裡有提到的效果)<br>extension HomeViewController: UIScrollViewDelegate {<br>    <br>    // scrollView開始滑動時，消除Timer<br>    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {<br>        if adImages.count &gt; 0 {<br>            stopTimer()<br>        }<br>    }<br>    <br>    // scrollView停止滑動時，生成Timer，開始輪播<br>    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer&lt;CGPoint&gt;) {<br>        if adImages.count &gt; 0 {<br>            setupTimer()<br>        }<br>    }<br>    <br>    // scrollView內容發生滾動時，無限輪播、PageControl轉跳<br>    func scrollViewDidScroll(_ scrollView: UIScrollView) {<br>        let currentX = adScrollView.contentOffset.x<br>        if currentX == 0 {<br>            let lastAdContentOffsetX = scrollView.frame.width * CGFloat(adImages.count)<br>            adScrollView.contentOffset = CGPoint(x: lastAdContentOffsetX, y: 0)<br>        } else if currentX == scrollView.frame.width * CGFloat(adImages.count + 1) {<br>            adScrollView.contentOffset = CGPoint(x: scrollView.frame.width, y: 0)<br>        }<br>        <br>        if scrollView == self.adScrollView {<br>            let page = round(scrollView.contentOffset.x / scrollView.frame.width) - 1<br>            self.adPageControl.currentPage = Int(page)<br>        }<br>    }<br>}</pre><h3>💙 參考及相關文章</h3><ul><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/stack-view-scroll-view-%E8%A3%BD%E4%BD%9C%E5%88%86%E9%A0%81-tutorial-%E6%87%B6%E5%BE%97%E5%AF%AB%E7%A8%8B%E5%BC%8F%E7%89%88-7ff9021317a0">stack view + scroll view 製作分頁 tutorial (懶得寫程式版)</a></li><li><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%BE%9E%E7%A8%8B%E5%BC%8F%E5%8B%95%E6%85%8B%E5%8A%A0-view-%E5%88%B0-stack-view-e5c2a2d01575">從程式動態加 view 到 stack view</a></li></ul><h3>💙 GitHub(會逐漸增長🤣)</h3><p><a href="https://github.com/labcgood/Kebuke">GitHub - labcgood/Kebuke</a></p><p>這次的App會先以寫死在專案裡的資料來練習，做完完整的App後會再接上API，我覺得這會讓整個App的開發過程更加有條理，增加理解度💪🏻</p><p>放颱風假，乖乖在家寫Code…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c2b8db0d1e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8scrollview-stackview%E5%81%9A%E5%87%BA%E8%87%AA%E5%8B%95%E8%BC%AA%E6%92%AD%E5%BB%A3%E5%91%8A%E5%8A%9F%E8%83%BD-7c2b8db0d1e0">🧋 33 訂飲料App-利用ScrollView+StackView做出自動輪播廣告功能</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>