<?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 Una on Medium]]></title>
        <description><![CDATA[Stories by Una on Medium]]></description>
        <link>https://medium.com/@hihi555000?source=rss-e51f6fabaff8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yXqbEjwmmKThnQNNn_dThQ.jpeg</url>
            <title>Stories by Una on Medium</title>
            <link>https://medium.com/@hihi555000?source=rss-e51f6fabaff8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:41:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hihi555000/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[來寫一個訂飲料app]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E4%BE%86%E5%AF%AB%E4%B8%80%E5%80%8B%E8%A8%82%E9%A3%B2%E6%96%99app-1ecca4de7f7c?source=rss-e51f6fabaff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ecca4de7f7c</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Una]]></dc:creator>
            <pubDate>Thu, 14 Sep 2023 15:37:21 GMT</pubDate>
            <atom:updated>2023-09-15T01:57:11.786Z</atom:updated>
            <content:encoded><![CDATA[<p>寫這個APP的時後發現最難的不是寫程式碼，而是調整auto layout及搜集飲料菜單把它寫成JSON，真的好瘋啊，第一次用auto layout的時候整整花了三天才稍稍可以切出一個像樣的版本。</p><p>今天就先來專案大致上的功能吧，並大概說一下每個頁面用到的技術。後續程式碼之後再詳細介紹 Let’s go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0rbryM8z5jxTtMDZal9iw.png" /><figcaption>所有畫面</figcaption></figure><blockquote><strong><em>學習目標</em></strong></blockquote><ul><li>Auto Layout</li><li>API串接</li><li>UserDefaults</li><li>airtable創建訂單資料</li><li>github創建JSON的飲料菜單API</li><li>FavQs模擬使用者登入拿token</li><li>collection view</li><li>UIAlertController</li></ul><blockquote><strong><em>成果 - 菜單頁面</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*F-zMObjcwKnqujccXXY_iQ.gif" /><figcaption>菜單頁面的操作</figcaption></figure><ul><li>banner使用scroll view + Timer.scheduledTimer做輪播</li><li>選單Bar下拉選單使用collection view切版</li><li>飲料List使用table view，將飲料分成多個section</li><li>使用github自己建立的Json Api 資料</li><li>使用@IBSegueAction將飲料選項資料傳遞到詳細頁</li></ul><blockquote><strong><em>成果 -菜單頁面</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*fMhCzckejPE8yYriAQwvNw.gif" /><figcaption>飲料詳細頁</figcaption></figure><ul><li>使用scroll view + Frame Layout做固定在底下的浮動元件</li><li>使用computed計算金額</li><li>UserDefaults取得登入者的名字，判斷是否需要導進登入頁面</li><li>利用airtable儲存訂單資訊</li><li>UIAlertController顯示提示訊息</li></ul><blockquote><strong><em>成果 - 登入頁面</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*8rYBdU31hjzVXcpAPlCYRA.gif" /><figcaption>登入及註冊畫面</figcaption></figure><ul><li>JSONEncoder及JSONDecoder解碼及編碼api資料</li><li>URLSession.shared.dataTask打api</li><li>FavQs模擬使用者登入拿token後，UserDefaults儲存登入者的名字</li><li>instantiateViewController及present跳轉回菜單頁面</li></ul><blockquote><strong><em>成果 — 訂單頁面</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*EL_qaj7OJqZIkOPuOVD73g.gif" /><figcaption>訂單頁面</figcaption></figure><ul><li>tableview的editingStyle做出刪除的方法</li><li>UIActivityIndicatorView做出api撈取資料的狀態</li><li>randomElement亂數隨機跑出頭像的emoji以及背景</li></ul><blockquote><strong><em>附上github</em></strong></blockquote><p><a href="https://github.com/hihiyuru/WOOTEA">GitHub - hihiyuru/WOOTEA</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ecca4de7f7c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E4%BE%86%E5%AF%AB%E4%B8%80%E5%80%8B%E8%A8%82%E9%A3%B2%E6%96%99app-1ecca4de7f7c">來寫一個訂飲料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[利用JSONDecoder串接第三方API]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8jsondecoder%E4%B8%B2%E6%8E%A5%E7%AC%AC%E4%B8%89%E6%96%B9api-2e6b831ac2b9?source=rss-e51f6fabaff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6b831ac2b9</guid>
            <category><![CDATA[ghibli]]></category>
            <category><![CDATA[tableviews]]></category>
            <category><![CDATA[jsondecoder]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Una]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 09:35:16 GMT</pubDate>
            <atom:updated>2023-08-22T14:23:30.295Z</atom:updated>
            <content:encoded><![CDATA[<p>拖了好久才又回來補文章，深怕再不寫，可能就會忘了當初怎麼寫的了。</p><p>一開始要著手這個作業時，最苦惱的就是要串什麼第三方API，在查的時候看到有神秘的open apiヽ(́◕◞౪◟◕‵)ﾉ最後還是選擇來串這個可愛的api就好哈哈，好了，那正片開始～</p><blockquote><strong><em>學習目標</em></strong></blockquote><ul><li>table view + controller view</li><li>JSONDecoder()</li><li>searchBar</li><li>使用第三方套件Kingfisher</li><li>WebKit</li></ul><blockquote><strong><em>最終成果</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*K6_4_aBLoRLv6O9RAgWMvQ.gif" /></figure><p>參考API來源：</p><ul><li><a href="https://github.com/kxvn-lx/Ghibliii">GitHub - kxvn-lx/Ghibliii: Studio Ghibli Movie database in Swift. For iOS, iPadOS, and MacOS.</a></li><li><a href="https://ghibliapi.vercel.app/">Studio Ghibli API</a></li><li><a href="https://github.com/n0shake/Public-APIs#entertainment">GitHub - n0shake/Public-APIs: 📚 A public list of APIs from round the web.</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/%E7%AC%AC%E4%B8%89%E6%96%B9-api-%E6%95%B4%E7%90%86-115868a56959">第三方 API 整理</a></li></ul><h4>📍api回傳類別定義：</h4><p>因為api回傳的資料有底線（snake case）因此在定義時，需要另外轉成我們的命名方法camel case。</p><pre>struct Movie: Decodable {<br>    let id: String<br>    let title: String<br>    let originalTitle: String<br>    let originalTitleRomanised: String<br>    let image: URL<br>    let movieBanner: URL<br>    let description: String<br>    let director: String<br>    let producer: String<br>    let releaseDate: String<br>    let runningTime: String<br>    let rtScore: String<br>    let url: String<br>    <br>    enum CodingKeys: String, CodingKey {<br>        case id<br>        case title<br>        case originalTitle = &quot;original_title&quot;<br>        case originalTitleRomanised = &quot;original_title_romanised&quot;<br>        case image<br>        case movieBanner = &quot;movie_banner&quot;<br>        case description<br>        case director<br>        case producer<br>        case releaseDate = &quot;release_date&quot;<br>        case runningTime = &quot;running_time&quot;<br>        case rtScore = &quot;rt_score&quot;<br>        case url<br>    }<br>}</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/%E5%88%A9%E7%94%A8-enum-codingkeys-%E5%AE%A2%E8%A3%BD-json-%E5%B0%8D%E6%87%89%E7%9A%84-property-1b27f29c0c32">利用 CodingKey 客製 JSON 對應的 property</a></p><h4>📍串接api：</h4><p>在電影列表的地方載入時就希望能拿到列表資料，因此使用 URLSession.shared.dataTask，並使用 JSONDecoder 串接api，最後當取得資要需要在main thread更新資料於是必須寫 Dispatch.main.async</p><p>其中因為tableview的UITableViewDataSource是用extension的方式寫在下方因此table view需要另外拉線定義使用</p><pre>@IBOutlet weak var ListTableView: UITableView!<br><br>override func viewDidLoad() {<br>  super.viewDidLoad()<br>  ListTableView.dataSource = self // 設定 tableView 的 dataSource<br>  fetchMovieList()<br>}<br>    <br>func fetchMovieList() {<br>  let urlString = &quot;https://ghibliapi.vercel.app/films&quot;<br>  guard let url = URL(string: urlString) else { return }<br>        <br>  URLSession.shared.dataTask(with: url) { data, response, error in<br>    if let data {<br>      let decoder = JSONDecoder()<br>      do {<br>        self.movies = try decoder.decode([Movie].self, from: data)<br>        self.showMovies = self.movies<br>        DispatchQueue.main.async {<br>          self.ListTableView.reloadData()<br>        }<br>        } catch {<br>          print(&quot;Erro decoding JSON: \(error)&quot;)<br>        }<br>      }<br>  }.resume()       <br>}</pre><h4>📍設定table view：</h4><p>在table view的每個cell有三個movie因此需要自定義cell</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74vX8Bf3twd0c_gTAPZnCQ.png" /><figcaption>在style選擇custom</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mybQft3KIpl9yK7odKGvMw.png" /><figcaption>table view也選擇Dynamic Prototypes模式，因為要經由api拿取資料</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkEn7nphOEqqyq3XHMMMhQ.png" /><figcaption>然後記得要拉dataSource到controllerView上</figcaption></figure><p>最後就是要讓高度正常顯示，可參考Peter的教學文章：</p><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%A6%82%E4%BD%95%E8%AE%93-table-view-cell-%E5%9B%BA%E5%AE%9A%E9%AB%98%E5%BA%A6-77e7ab6f6a4">如何讓 table view cell 固定高度</a></p><h4>📍處理cell中三個電影的顯示：</h4><p>在table view中，有處理cell的方法，可以用indexPath.row直接拿取陣列的資料，但因為cell有三個項目，因此需要另外處理。</p><p>每個cell都讀取api資料的3個項目：</p><pre>// 實作 UITableViewDataSource 協定<br>extension MovieListViewController: UITableViewDataSource {<br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        return showMovies.count / 3    // 計算顯示的資料列數<br>    }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        // 取得自定義的 ListTableViewCell<br>        guard let cell = tableView.dequeueReusableCell(withIdentifier: &quot;\(ListTableViewCell.self)&quot;, for: indexPath) as? ListTableViewCell else {<br>            fatalError(&quot;Something went wrong with dequeuing the cell.&quot;)<br>        }<br>        <br>        // 取消選取效果<br>        cell.selectionStyle = .none    <br>        <br>        // 計算每個資料列要顯示的電影範圍<br>        let startMovieIndex = indexPath.row * 3<br>        let endMovieIndex = min(startMovieIndex + 3, showMovies.count)<br>        let rowMovies = Array(showMovies[startMovieIndex..&lt;endMovieIndex])<br>        <br>        // 更新 cell 中的電影標題、發行日期和海報圖片<br>        for (index, label) in cell.movieNameLabels.enumerated() {<br>            if index &lt; rowMovies.count {<br>                label.text = rowMovies[index].title<br>            } else {<br>                label.text = nil<br>            }<br>        }<br>        <br>        for (index, label) in cell.yearLabels.enumerated() {<br>            if index &lt; rowMovies.count {<br>                label.text = rowMovies[index].releaseDate<br>            } else {<br>                label.text = nil<br>            }<br>        }<br>        <br>        for (index, pic) in cell.posterImageViews.enumerated() {<br>            if index &lt; rowMovies.count {<br>                pic.kf.setImage(with: rowMovies[index].image)<br>            } else {<br>                pic.image = nil<br>            }<br>        }<br>        <br>        return cell<br>    }<br>}</pre><h4>📍把資料傳到下一頁：</h4><p>每個cell有3個項目因此會有3個@IBSegueAction來傳他們的id，在下一頁拿到id後可以再用其他api拿取電影的詳細資料。</p><pre>@IBSegueAction func showDetail3(_ coder: NSCoder, sender: Any?) -&gt; MovieDetailViewController? {<br>  let controller =  MovieDetailViewController(coder: coder)<br>  controller?.movieId = selectedMovie?.id<br>  return controller<br>}<br><br>@IBSegueAction func showDetail2(_ coder: NSCoder, sender: Any?) -&gt; MovieDetailViewController? {<br>  let controller =  MovieDetailViewController(coder: coder)<br>  controller?.movieId = selectedMovie?.id<br>  return controller<br>}<br><br>@IBSegueAction func showDetail1(_ coder: NSCoder, sender: Any?) -&gt; MovieDetailViewController? {<br>  let controller =  MovieDetailViewController(coder: coder)<br>  controller?.movieId = selectedMovie?.id<br>  return controller<br>}</pre><h4>📍searchBar：</h4><p>因為searchBar搜尋後條件會改變，並不想每次搜尋都打api因此需要用兩個陣列來儲存，一個用來儲存api回傳的所有的電影資料，一個用來儲存需要顯示的電影資料，最後也需要reloadData()，table view才會進行更新</p><pre>var movies: [Movie] = [] // api拿的所有movie<br>var showMovies: [Movie] = [] // 需要顯示在畫面的movie<br><br>extension MovieListViewController: UISearchBarDelegate {<br>    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {<br>        if let searchText = searchBar.text, searchBar.text != &quot;&quot;{<br>            // 過濾出搜尋列有包含的的單字電影<br>            let searchMovie = movies.filter { movie in<br>                movie.title.contains(searchText)<br>            }<br>            showMovies = searchMovie<br>            ListTableView.reloadData() // 重新載入 TableView<br>        } else {<br>            showMovies = movies<br>            ListTableView.reloadData()<br>        }<br>        searchBar.resignFirstResponder() // 關閉鍵盤<br>    }<br>    <br>}</pre><blockquote><strong><em>附上github</em></strong></blockquote><p><a href="https://github.com/hihiyuru/Ghibli-movie">GitHub - hihiyuru/Ghibli-movie</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6b831ac2b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E5%88%A9%E7%94%A8jsondecoder%E4%B8%B2%E6%8E%A5%E7%AC%AC%E4%B8%89%E6%96%B9api-2e6b831ac2b9">利用JSONDecoder串接第三方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[寫一個猜燈謎的小遊戲]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E5%AF%AB%E4%B8%80%E5%80%8B%E7%8C%9C%E7%87%88%E8%AC%8E%E7%9A%84%E5%B0%8F%E9%81%8A%E6%88%B2-587bd4c12881?source=rss-e51f6fabaff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/587bd4c12881</guid>
            <category><![CDATA[games]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[emoji]]></category>
            <dc:creator><![CDATA[Una]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 19:23:20 GMT</pubDate>
            <atom:updated>2023-08-07T08:06:59.839Z</atom:updated>
            <content:encoded><![CDATA[<p>剛要練習這個主題，立馬想到知識王LIVE，記得以前很愛跟朋友玩知識王LIVE，但我們不是一起跟人PK，是一起回答同一個問題去打敵人(☝ ՞ਊ ՞）☝嘿嘿，但又看到他出了另一個遊戲APP，表情符號王，立馬下載，原本要做作業，結果自己玩了1個小時…超好玩</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*hAuKFTFPATKbsZ38OSD0lA.gif" /></figure><p>所以！決定自己來做看看～Let’s Go!</p><blockquote><strong><em>學習目標</em></strong></blockquote><ul><li>for 迴圈</li><li>if else</li><li>array</li><li>亂數</li><li>自訂資料型別</li><li>MVC分類檔案</li><li>專案資料</li><li>computed property</li><li>property observer</li><li>頁面之間傳遞資料</li></ul><blockquote><strong><em>最終成果</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*2PvWpa5ef0LSEkmF-1ficw.gif" /></figure><p><a href="https://youtube.com/shorts/hl7KlnTa5zQ?feature=share">emoji猜成語</a></p><p>遊戲參考資料：</p><ul><li><a href="https://apps.apple.com/tw/app/%E8%A1%A8%E6%83%85%E7%AC%A6%E8%99%9F%E7%8E%8B/id1476412372?l=en-GB">‎表情符號王</a></li><li><a href="https://ppfocus.com/mo/0/fa7563ed5.html">元宵猜謎匯｜emoji表情猜謎，你都能猜到是什麼成語嗎？ - 人人焦點</a></li></ul><h4>📍MVC分類檔案：</h4><p>在這次專案中我將資料分為Models及View Controllers進行管理。</p><ul><li>Models: 我就會放自己定義的資料型別</li><li>View Controllers: 我就會放每個畫面的程式碼</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*sqPKDhAd3SDhDVg8JMaFHQ.png" /></figure><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-app-%E7%9A%84-xcode-%E5%B0%88%E6%A1%88%E5%A6%82%E4%BD%95%E5%88%86%E9%A1%9E%E6%AA%94%E6%A1%88-project-organization-e18d6fb5060a">iOS MVC App 的 Xcode 專案如何分類檔案(project organization)</a></p><h4>📍創建型別：</h4><p>這個遊戲需要很多題目，於是在models裡建立一個Question的型別，之後好用來生成一個題庫的陣列。在這個類別中需要三個參數分別為：題目，答案，魚目混珠的文字。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*iuP6MRR5s1yJVw6n1VyanQ.png" /><figcaption>題目，答案，魚目混珠的文字</figcaption></figure><p>在這裡面我希望生成10個隨機的中文字，因此我需要先用一個generateRandomChineseCharacters的方法隨機創建10個文字</p><pre>func generateRandomChineseCharacters(count: Int) -&gt; [String] {<br>    var result: [String] = []<br>    <br>    for _ in 0..&lt;count {<br>       // 使用 arc4random_uniform 函數生成一個介於 0x3400 和 0x4E00 - 1 之間的隨機數。這些數值範圍包含了中文字符的 Unicode 範圍。<br>        let randomUnicodeValue = arc4random_uniform(UInt32(0x4E00 - 0x3400)) + UInt32(0x3400)<br>        <br>        if let scalar = Unicode.Scalar(randomUnicodeValue) {<br>            let character = Character(scalar)<br>            result.append(String(character))<br>        }<br>    }<br>    <br>    return result<br>}</pre><p>創建完10個隨機文字後，需要將真正的答案加入隨機文字陣列中，但只加在後面當然不行，因此需要使用shuffle()來讓陣列裡面的元素隨機排列。</p><pre>func getRandomChineseCharacters(anser: [String]) -&gt; [String] {<br>    // 加入真正的答案，兩個變數的類型都為[String]因此可以直接用加號<br>    var allCharacters = generateRandomChineseCharacters(count: 10) + anser<br>    // 陣列裡面的元素隨機排列<br>    allCharacters.shuffle()<br>    return allCharacters<br>}</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/swift-4-2-%E6%9B%B4%E6%96%B9%E4%BE%BF%E7%9A%84%E4%BA%82%E6%95%B8-random-function-85fa69a08215">Swift 4.2 更方便的亂數 function，random，randomElement &amp; shuffle</a></p><p>在GameViewController使用：</p><pre>var gameDatas: [Question] = [<br>  Question(topic: [&quot;🐯&quot;, &quot;🐯&quot;, &quot;🐯&quot;, &quot;🐯&quot;], ans: [&quot;虎&quot;, &quot;頭&quot;, &quot;虎&quot;, &quot;腦&quot;]),<br>  Question(topic: [&quot;👣&quot;, &quot;📈&quot;, &quot;💨&quot;, &quot;🤷‍♂️&quot;], ans: [&quot;趾&quot;, &quot;高&quot;, &quot;氣&quot;, &quot;揚&quot;]),<br>  Question(topic: [&quot;😈&quot;, &quot;💬&quot;, &quot;💔&quot;, &quot;👤&quot;], ans: [&quot;惡&quot;, &quot;語&quot;, &quot;傷&quot;, &quot;人&quot;]),<br>  Question(topic: [&quot;1️⃣&quot;, &quot;🎵&quot;, &quot;🤯&quot;, &quot;👤&quot;], ans: [&quot;一&quot;, &quot;鳴&quot;, &quot;驚&quot;, &quot;人&quot;]),<br>  // ...省略其他<br>]</pre><h4>📍關卡更新：</h4><p>在初始時就會生成第一關所以當一開始所有gameDatas都準備好的時候，每次都會進到updateLevel()拿新的一關，並且移除掉gameDatas已經玩過的題目，直到gameDatas沒有資料，遊戲結束。</p><pre>func updateLevel() {<br>  // 判斷還有沒有題目<br>  if !gameDatas.isEmpty {<br>    // 用過的題目就移除<br>    levelData = gameDatas.removeFirst()<br>    if let question = levelData {<br>      // 更新題目標籤<br>      for (index, label) in topicLabel.enumerated() {<br>        if index &lt; question.topic.count {<br>          label.text = question.topic[index]<br>        }<br>      }<br>      // 更新按鈕文字<br>      for (index, button) in wordsButton.enumerated() {<br>        if index &lt; question.others.count {<br>          button.setTitle(question.others[index], for: .normal)<br>        }<br>      }<br>    }<br>  } else {<br>    gameOverView.isHidden = false<br>  }       <br>}</pre><h4>📍點擊文字按鈕：</h4><p>因為我要做動畫，所以必須記錄按鈕要飛到哪。可以打開stoybroad查看答案方框的位置在哪。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*rhuwPyeEoZwU59Lk4VLJBg.png" /><figcaption>查看方框位置在哪裡</figcaption></figure><p>點擊第一次位置是1點;擊點第二次位置是2以此類推，找出每個位置，寫switch做判斷。</p><pre>let targetY: CGFloat = 425<br>var targetX: CGFloat<br><br>clickAnsCount += 1<br>switch clickAnsCount {<br>case 1:<br>  targetX = 94<br>            <br>case 2:<br>  targetX = 155<br>            <br>case 3:<br>  targetX = 215<br>            <br>case 4:<br>  targetX = 276<br>            <br>default:<br>  targetX = 94<br>}</pre><p>設定好每次需要移動到的位置後，可以用animate來設定需要移動到的CGPoint，並且移動後的按鈕都不能再點擊。</p><pre>// 移動按鈕位置並禁用<br>UIView.animate(withDuration: 0.5) {<br>  sender.frame.origin = CGPoint(x: targetX, y: targetY)<br>  sender.isEnabled = false<br>  sender.backgroundColor = .white<br>  sender.layer.cornerRadius = 5<br>  sender.setTitleColor(.darkGray, for: .disabled)<br> }</pre><p>另外因為動畫會需要時間跑所以如果沒有延遲更新下一關的話，第四顆鈕就會跑不出來，直接到下一關，我們必須設定類似setTimeout的佇列才能避免這個狀況。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*Xi3NwFWmVk5YgSj8cDSJJw.gif" /><figcaption>不等第四顆按鈕出現就跑下一關了</figcaption></figure><pre>let delayInSeconds: Double = 1.0 // 延遲 1 秒<br>// 延遲一段時間後執行的程式碼<br>DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { [self] in<br>  // 在這裡放置延遲執行的程式碼<br>  if self.isGameOver {<br>    self.gameOverView.isHidden = false<br>  } else {<br>    self.initUI()<br>    self.updateLevel()<br>  }                 <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*xree3eODtNHHMZcSbCwFIg.gif" /><figcaption>等待一秒後才換下一關</figcaption></figure><p>應該有發現在下一關的時候需要讓按鈕都乖乖回去，所以必須在viewDidLoad()的時候就記下所有按鈕的位置，在更新關卡的時候才能讓按鈕乖乖回去。</p><pre>override func viewDidLoad() {<br>  super.viewDidLoad()<br>  setOriginalButtonPosition()<br>}<br><br>// 設定按鈕的初始位置<br>func setOriginalButtonPosition() {<br>  for word in wordsButton {<br>    originalButtonPosition.append(word.frame.origin)<br>  }<br>}<br><br>// 初始化界面元素<br>func initUI() {<br>  for (index, word) in wordsButton.enumerated() {<br>    // 更新關卡讓按鈕各自歸位，並且恢復可以點擊<br>    UIView.animate(withDuration: 0.5) {<br>      word.frame.origin = self.originalButtonPosition[index]<br>      word.isEnabled = true<br>     }<br>   }<br>}</pre><h4>📍computed property：</h4><pre>// 判斷遊戲是否結束的計算屬性<br>var isGameOver: Bool {<br>  return heartsImageView.isEmpty<br>}</pre><h4>📍property observer：</h4><pre>// 紀錄玩家獲勝次數，屬性觀察器會自動更新界面<br>var winAcount = 0 {<br>  didSet {<br>    winAcountLabel.text = String(winAcount)<br>  }<br>}</pre><h4>📍頁面間的溝通：</h4><p>需要使用到@IBSegueAction，產生這個方法的方式跟產生@IBAction一樣，只需要找到Segue然後按著control即可。特別注意：在結果頁，因為class裡面的參數是需要初始值，不然就是必須定義為optional，因此我確定我一定會傳資料過去，所以給“！”告訴他，我一定要取資料</p><pre>// 在結果頁接收資料<br>class resultViewController: UIViewController {<br>    // 我一定要取資料，強制取資料，但沒有的話就壞掉，特別注意<br>    var heartsAcount: Int!<br><br>    @IBOutlet weak var resultImageView: UIImageView!<br>    @IBOutlet weak var resultLabel: UILabel!<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        showResult()<br>        <br>    }<br>    <br>    func showResult() {<br>        if heartsAcount &gt; 0 {<br>            resultImageView.image = UIImage(named: &quot;win&quot;)<br>            resultLabel.text = &quot;LEVEL UP&quot;<br>        } else {<br>            resultImageView.image = UIImage(named: &quot;lose&quot;)<br>            resultLabel.text = &quot;You LOSE!&quot;<br>        }<br>    }<br>}</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/%E5%88%A9%E7%94%A8-ibsegueaction-%E5%82%B3%E8%B3%87%E6%96%99%E5%88%B0%E4%B8%8B%E5%80%8B%E9%A0%81%E9%9D%A2%E7%9A%84-controller-ios-13-%E6%96%B0%E5%8A%9F%E8%83%BD-50813ba3822">利用 IBSegueAction 傳資料到下個頁面的 controller — iOS 13 新功能</a></p><blockquote><strong><em>附上github</em></strong></blockquote><p><a href="https://github.com/hihiyuru/emoji-game">GitHub - hihiyuru/emoji-game</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=587bd4c12881" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E5%AF%AB%E4%B8%80%E5%80%8B%E7%8C%9C%E7%87%88%E8%AC%8E%E7%9A%84%E5%B0%8F%E9%81%8A%E6%88%B2-587bd4c12881">寫一個猜燈謎的小遊戲</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[做一個分帳APP]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E5%81%9A%E4%B8%80%E5%80%8B%E5%88%86%E5%B8%B3app-cb4e17b24812?source=rss-e51f6fabaff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb4e17b24812</guid>
            <category><![CDATA[split-bills]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Una]]></dc:creator>
            <pubDate>Wed, 02 Aug 2023 17:58:42 GMT</pubDate>
            <atom:updated>2023-08-03T08:56:56.533Z</atom:updated>
            <content:encoded><![CDATA[<p>想到每次跟高中朋友出門都讓會計朋友幫忙算大家的費用，這次就做個分帳的app稍微減輕一下她的負擔吧～</p><blockquote><strong><em>學習目標</em></strong></blockquote><ul><li>字串與數字之間的類型轉換</li><li>可以重新計算分帳金額</li><li>鍵盤收起方式</li><li>optional binding</li></ul><blockquote><strong><em>最終成果</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*tCLvEky2_48AirDVJHZrVg.gif" /></figure><p>這次的UI參考了網路上的大神做出來的，附上連結：</p><p><a href="https://dribbble.com/shots/4413821-Split-bill-Interaction">Split bill Interaction</a></p><h4><strong>📍UISlider樣式：</strong></h4><p>這是研究蠻久slider的樣式，原本想說要改變slider的高度，但發現怎麼改都沒有用，於是找到彼得潘的文章，原來只要用圖片的高度來撐就可以了，當下看到解決方法都要流下淚了。附上教學文上連結：</p><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%AE%A2%E8%A3%BD-uikit-%E7%9A%84-uislider-%E6%A8%A3%E5%BC%8F-cee49b5038c0">客製 UIKit 的 UISlider 樣式</a></p><h4>📍optional binding：</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*M0qqO8lsajAE7TJLn9zdmg.png" /><figcaption>使用TextField自訂小費的趴數</figcaption></figure><p>這次學習的重點之一，在小費自訂趴數的TextField為optional，因此使用if let來判斷，並且TextField為string需要轉換為Int才能使用。</p><pre>@IBAction func typingPercent(_ sender: UITextField) {<br>  if let percentText = sender.text {<br>    // “！”告訴他我一定取得到 <br>    percent = Int(percentText)!<br>  } else {<br>    percent = 0<br>  }<br>}</pre><h4>📍button的tag：</h4><p>這次按鈕的button我都設置了tag直接設定為按鈕對應的數字，而tag的屬性就為Int所以不需要特別做處理。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*Fv2_HCh5N_eYYdJlo2BxRQ.png" /></figure><pre>@IBAction func onClickNumber(_ sender: UIButton) {<br>  // 按下數字按鈕，更新目前輸入的金額<br>  let number = sender.tag<br>  currentNumber = currentNumber * 10 + number<br>  totalLabel.text = &quot;\(currentNumber)&quot;<br>  smallTatolLabel.text = &quot;NT$\(currentNumber)&quot;<br>}</pre><h4>📍鍵盤收起：</h4><p>這次使用到鍵盤收起有兩個地方，在打分帳標題時，使用到按done就可以收起，以及輸入小費時按空白處可以收起，附上教學文：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*T9ggdy645H0AJtYSpGHUUw.gif" /></figure><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/uikit-app-%E6%8C%89%E7%A9%BA%E7%99%BD%E8%99%95%E6%94%B6%E9%8D%B5%E7%9B%A4%E7%9A%84%E6%96%B9%E6%B3%95-97a676338e86">UIKit 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/uitextfield-%E9%BB%9E%E9%81%B8-return-%E9%8D%B5%E6%94%B6%E9%8D%B5%E7%9B%A4%E7%9A%84%E6%96%B9%E6%B3%95-f99769370d46">UITextField 點選 return 鍵收鍵盤的方法</a></li></ul><blockquote>附上github</blockquote><p><a href="https://github.com/hihiyuru/split-bill">GitHub - hihiyuru/split-bill</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb4e17b24812" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E5%81%9A%E4%B8%80%E5%80%8B%E5%88%86%E5%B8%B3app-cb4e17b24812">做一個分帳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[來寫個簡單的音樂播放器（下）]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E4%BE%86%E5%AF%AB%E5%80%8B%E7%B0%A1%E5%96%AE%E7%9A%84%E9%9F%B3%E6%A8%82%E6%92%AD%E6%94%BE%E5%99%A8-%E4%B8%8B-bfa7a2f99109?source=rss-e51f6fabaff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfa7a2f99109</guid>
            <category><![CDATA[avfoundation]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[music-player]]></category>
            <dc:creator><![CDATA[Una]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 10:33:57 GMT</pubDate>
            <atom:updated>2023-07-27T14:34:23.420Z</atom:updated>
            <content:encoded><![CDATA[<p>結果還是做了下集，而且事實上一點都不簡單..好多語法都不是很熟悉，花好多時間查及看文章，歌詞依舊沒做出來等到有做出來再來更新～</p><blockquote><strong>上集在這裡</strong></blockquote><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/%E4%BE%86%E5%AF%AB%E5%80%8B%E7%B0%A1%E5%96%AE%E7%9A%84%E9%9F%B3%E6%A8%82%E6%92%AD%E6%94%BE%E5%99%A8%E7%95%8C%E9%9D%A2-%E4%B8%8A-9f3230fd0934">來寫個簡單的音樂播放器（上）</a></p><blockquote><strong>最終成果</strong></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjSjzs5olee8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjSjzs5olee8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FjSjzs5olee8%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/fd5586614b5b2bbd284eeea528d2d631/href">https://medium.com/media/fd5586614b5b2bbd284eeea528d2d631/href</a></iframe><p><strong>1/</strong>延續上集UI介面稍微調整了一下，包含背景改成漸層，播放按鍵原本用image設定，但需要寫程式改尺寸稍嫌麻煩改為Background的方式..等</p><ul><li>背景改為漸層</li></ul><pre>func setupGradientBackground() {<br>  let gradientLayer = CAGradientLayer()<br>  gradientLayer.frame = view.bounds<br>  gradientLayer.colors = [<br>  CGColor(srgbRed: 53/255, green: 91/255, blue: 98/255, alpha: 1),<br>  CGColor(srgbRed: 31/255, green: 49/255, blue: 57/255, alpha: 1)<br>  ]<br>  view.layer.insertSublayer(gradientLayer, at: 0)<br>}</pre><p>參考資料：</p><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-cagradientlayer-%E8%A3%BD%E4%BD%9C%E6%BC%B8%E5%B1%A4%E8%83%8C%E6%99%AF-a10c7cfd7f75">利用 CAGradientLayer 製作漸層背景</a></p><ul><li>播放的UIButton改為Background顯示，依照下圖修改button就可以讓圖示跟按鈕外框的大小一致。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*GHwz8FHZ6cgDLg050rSRFw.png" /></figure><ul><li>slider thumb改大小</li></ul><pre>func setupSlider() {<br>  let thumbImage = UIImage(systemName: &quot;circle.fill&quot;, withConfiguration: UIImage.SymbolConfiguration(pointSize: 15))<br>  timeSlider.setThumbImage(thumbImage, for: .normal)<br>  timeSlider.tintColor = .white<br>}</pre><p>以為這樣改完就好了結果再滑動的時候發生離奇的變大事件</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*V7d1PH5POsuj3VoT5_qZ6Q.gif" /><figcaption>拉動時就自己變大</figcaption></figure><p>才發現原來是在storyboard的時候應該要Thumb Tint改為default</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*YNgIc5o68vg_XJVAOyQEPQ.png" /></figure><p>2/slider音樂時間軸，需要取得音樂總時長，已經經過的時間，所以會需要用到CMTime，player.addPeriodicTimeObserve</p><ul><li><strong>CMTime說明</strong></li></ul><pre>// CMTime 的定義<br>struct CMTime {<br><br>    // 表示的時間值。它表示時間的數量，例如影片的第幾幀或音訊樣本的數量。<br>    var value: CMTimeValue<br><br>    // 表示的時間刻度。它表示每秒的時間刻度數量，用於計算時間的單位，例如 30 表示每秒 30 幀。<br>    var timescale: CMTimeScale<br><br>    // 表示的標誌。這是一些標誌位，用於指示時間的一些特殊屬性，例如是否是無限時間、是否溢出等。<br>    var flags: CMTimeFlags<br><br>    // 表示的時間的開始點。它通常是 0，但在某些情況下，可以用來表示不同的時間起點。<br>    var epoch: CMTimeEpoch<br>}<br></pre><p>建立 CMTime 物件：</p><pre>let timeValue = CMTimeValue(60) // 60 個時間單位<br>let timeScale = CMTimeScale(1) // 1 秒內的時間刻度<br>let time = CMTime(value: timeValue, timescale: timeScale)</pre><p>將 CMTime 轉換為秒數：</p><pre>let seconds = CMTimeGetSeconds(time)</pre><p>進行時間的比較：</p><pre>let time1 = CMTime(value: 60, timescale: 1) // 60 秒<br>let time2 = CMTime(value: 30, timescale: 1) // 30 秒<br><br>if CMTimeCompare(time1, time2) == 1 {<br>    print(&quot;time1 is greater than time2&quot;)<br>} else if CMTimeCompare(time1, time2) == -1 {<br>    print(&quot;time1 is less than time2&quot;)<br>} else {<br>    print(&quot;time1 and time2 are equal&quot;)<br>}</pre><p>進行時間的加減：</p><pre>let time1 = CMTime(value: 60, timescale: 1) // 60 秒<br>let time2 = CMTime(value: 30, timescale: 1) // 30 秒<br><br>let sumTime = CMTimeAdd(time1, time2) // 90 秒<br>let subtractTime = CMTimeSubtract(time1, time2) // 30 秒</pre><p>進行時間的乘法和除法</p><pre>let time1 = CMTime(value: 60, timescale: 1) // 60 秒<br><br>let multipliedTime = CMTimeMultiplyByFloat64(time1, multiplier: 2.5) // 150 秒<br>let dividedTime = CMTimeMultiplyByFloat64(time1, multiplier: 0.5) // 30 秒</pre><ul><li><strong>addPeriodicTimeObserver說明</strong></li></ul><p>是 AVPlayer 的一個方法，用於註冊一個定期調用的觀察者，以便在播放進度改變時接收通知。</p><pre>func addSongDuration() {<br>  // timeScale 是 CMTimeScale 類型的變數，它用於表示時間刻度的數量。在這裡，我們使用 NSEC_PER_SEC，它是一個宏，表示每秒的納秒數。將這個時間刻度作為 addPeriodicTimeObserver 的間隔，意味著觸發頻率將是每秒一次。<br>  let timeScale = CMTimeScale(NSEC_PER_SEC)<br>  // interval 是 CMTime 類型的變數，它用於表示時間間隔。這裡我們使用 CMTime 的便利初始化方法 seconds:preferredTimescale:，將 seconds 參數設置為 1 秒，並將 preferredTimescale 參數設置為前面定義的 timeScale 變數，這樣我們就得到了每秒一次的時間間隔。<br>  let interval = CMTime(seconds: 1, preferredTimescale: timeScale)<br>  // mainQueue 是一個 DispatchQueue，它用於在主線程上運行觸發的 closure。由於在觸發進度觀察器的 closure 時，通常會更新 UI 或其他與主線程相關的操作，因此我們將觸發的 closure 放在主線程上執行，以避免在非主線程上進行 UI 更新而導致的問題。<br>  let mainQueue = DispatchQueue.main<br>        <br>  timeObserverToken = player.addPeriodicTimeObserver(forInterval: interval, queue: mainQueue) { [weak self] time in<br>    // ... 這裡是觀察到的時間變化的處理程式碼<br>  }<br>}</pre><ul><li><strong>哪裡加監控</strong></li></ul><p>因為切換每首歌的時候就需要相關的資料內容，於是我加在changeSong的function中</p><pre>// 添加歌曲播放時間觀察器<br>func addSongDuration() {<br>  let timeScale = CMTimeScale(NSEC_PER_SEC)<br>  let interval = CMTime(seconds: 1, preferredTimescale: timeScale)<br>  let mainQueue = DispatchQueue.main<br>        <br>  timeObserverToken = player.addPeriodicTimeObserver(forInterval: interval, queue: mainQueue) { [weak self] time in<br>  guard let self = self else { return } // 使用weak self避免retain cycle<br>            <br>  if self.player.timeControlStatus == .playing {<br>    // 取得歌曲總長度<br>    let songDuration = self.player.currentItem?.duration<br>    let formattedDuration = self.formatTimeDuration(songDuration)<br>                <br>    // 取得當前播放時間<br>    let currentTime = CMTimeGetSeconds(time)<br>    let formattedCurrentTime = self.formatTimeDuration(CMTime(seconds: currentTime, preferredTimescale: timeScale))<br>                <br>    // 更新播放時間的 UI 顯示<br>    self.setTimeUI(passTime: formattedCurrentTime, durationTime: formattedDuration)<br>  }<br>}<br><br>// 更新歌曲資訊及視圖顯示<br>func changeSong() {<br>   // ...其他程式碼先忽略<br><br>    // 重新加入時間觀察器<br>   addSongDuration()<br>}</pre><p>後來加完監控後，切換下一首歌時出現Thread 1: Fatal error: Double value cannot be converted to Int because it is either infinite or NaN的錯誤</p><p>其原因因為在播放下一首歌曲時，監控正在觀察上一首歌曲，但當音樂換曲時未有效更新，導致出現錯誤。解決這個問題的方法是在切換歌曲前，先移除之前的時間觀察器，避免不必要的回調，然後在切換完歌曲後再重新加入時間觀察器。</p><p>於是在切換歌曲時都需要先移除監控：</p><pre>// 移除時間觀察器的方法<br>func removeTimeObserver() {<br>    if let token = timeObserverToken {<br>        player.removeTimeObserver(token)<br>        timeObserverToken = nil<br>    }<br>}<br><br>func preSong() {<br>    // ...省略其他程式碼<br>    removeTimeObserver() // 移除時間觀察器<br>    changeSong()<br>}<br><br>func nextSong() {<br>    // ...省略其他程式碼<br>    removeTimeObserver() // 移除時間觀察器<br>    changeSong()<br>}<br><br>func changeSong() {<br>    // ... 其他程式碼 ...<br><br>    // 移除前一首歌曲的時間觀察器<br>    removeTimeObserver()<br>    <br>    // 切換歌曲<br>    replaceSong()<br>    <br>    // 重新加入時間觀察器<br>    addSongDuration()<br>}</pre><ul><li><strong>實現拉動改變歌曲播放時間</strong></li></ul><p>我們必須要知道使用者放開的時候時間軸到哪裡了，所以UISlider有一個屬性為isTracking用來監控是不是放開了</p><pre>// 修改歌曲播放進度的IBAction<br>@IBAction func changeTime(_ sender: UISlider) {<br>if sender.isTracking {<br>    let time = CMTime(value: CMTimeValue(Int(sender.value)), timescale: 1)<br>    player.seek(to: time)<br>    player.play()<br>  }<br>}</pre><p>這樣寫完之後發現thumb在播放中拉一次就會抖動，原因是因為在 addSongDuration() 方法中，每秒鐘都會更新一次 UISlider 的 value 屬性，以顯示目前播放的進度。而在這個更新的過程中，UISlider 的 value 屬性會被改變，這導致了抖動的現象。</p><p>於是在每次放開後我會判斷是否為播放中的音樂，然後先暫停音樂，等調整好播放區間才開始播音樂</p><pre>@IBAction func changeTime(_ sender: UISlider) {<br>        <br>  if sender.isTracking {<br>    // 判斷是否為播放中的音樂<br>    let isCurrentPlaying = player.timeControlStatus == .playing ? true : false<br>    // 是播放中的音樂就先暫停<br>    if isCurrentPlaying {<br>      player.pause()<br>    }<br>    let time = CMTime(value: CMTimeValue(Int(sender.value)), timescale: 1)<br>    player.seek(to: time)<br>    // 是播放中的音樂再繼續播放<br>    if isCurrentPlaying {<br>      player.play()<br>    }<br>  }<br>}</pre><p>3/播放完一首後繼續播放，需要用到NotificationCenter.default.addObserver的方法</p><ul><li>NotificationCenter.default.addObserver說明</li></ul><pre>// observer: 要註冊的觀察者，通常是一個物件，該物件需要能夠接收並處理特定通知。<br>// selector: 接收通知時要呼叫的方法，這個方法需要符合Selector型別，通常會使用#selector語法來指定對應的方法。<br>// name: 要監聽的通知名稱，通知的名稱通常是一個唯一的字串，用來標識不同的通知。如果想要接收所有通知，可以設定為nil。<br>// object: 通知的發送者，可以設定為特定物件來過濾只接收該物件發送的通知，或者設定為nil接收所有來自任意物件的通知。<br>class MyViewController: UIViewController {<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // 註冊觀察者來接收名稱為&quot;myNotification&quot;的通知<br>        NotificationCenter.default.addObserver(self, selector: #selector(handleNotification(_:)), name: Notification.Name(&quot;myNotification&quot;), object: nil)<br>    }<br>    <br>    @objc func handleNotification(_ notification: Notification) {<br>        // 在這裡處理收到的通知<br>        // 你可以透過`notification.userInfo`取得通知中附帶的資訊<br>        if let userInfo = notification.userInfo {<br>            // 根據userInfo中的資訊進行處理<br>        }<br>    }<br>}</pre><p>這裡我們需要在一開始就掛載這個方法（viewDidLoad中），播完歌後就會自動調用他</p><pre>override func viewDidLoad() {<br>// 省略其他程式碼...<br>NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil, queue: .main) { _ in<br>  if self.isRepeat {<br>    self.repeatSong()<br>  } else if !self.isRandom {<br>    self.nextSong()<br>  } else {<br>    self.randomSong()<br>  }<br>  self.playSong()        <br>  }<br>}</pre><p><strong>4/隨機播放音樂</strong></p><ul><li>在全局設定一個變數儲存是不是隨機模式變數</li></ul><pre>var isRandom = false</pre><ul><li>在隨機的按鈕上綁定Action事件</li></ul><pre>// 隨機播放按鈕的IBAction<br>@IBAction func onRandom(_ sender: UIButton) {<br>  isRandom = !isRandom<br>}</pre><ul><li>建立隨機播放的事件，為了避免隨機到現在正在播的歌曲於是需要使用repeat…while來做判斷</li></ul><pre>// 隨機播放下一首歌曲<br>func randomSong() {<br>  var randomIndex: Int = currentIndex // 將 randomIndex 初始化為 currentIndex 的初始值<br>  repeat {<br>    randomIndex = Int.random(in: 0...2)<br>  } while randomIndex == currentIndex<br>   logger.log(&quot;進入隨機 \(randomIndex)&quot;)<br>   removeTimeObserver()<br>   currentIndex = randomIndex<br>   changeSong()<br>}</pre><ul><li>放到切換歌曲的事件中</li></ul><pre><br>override func viewDidLoad() {<br>// 當一首歌播完時<br>  NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil, queue: .main) { _ in<br>    if self.isRepeat {<br>      self.repeatSong()<br>    } else if !self.isRandom {<br>      self.nextSong()<br>    } else {<br>      self.randomSong()<br>    }<br>      self.playSong() <br>    }<br>}<br><br>// 切換到下一首歌曲<br>func nextSong() {<br>  if !isRandom {     <br>    currentIndex = (currentIndex == songs.count - 1) ? 0 : (currentIndex + 1)<br>    removeTimeObserver()<br>    changeSong()<br>  } else {<br>    randomSong()<br>  }<br>}</pre><p><strong>5/重複播放</strong></p><ul><li>在全局設定一個變數儲存是不是重複播放模式變數</li></ul><pre>var isRepeat = false</pre><ul><li>在重複播放按鈕新增Action事件</li></ul><pre>// 重複播放按鈕的IBAction<br>@IBAction func onRepeat(_ sender: UIButton) {<br>  isRepeat = !isRepeat<br>  // 根據 isRepeat 的狀態來更改重複播放按鈕的圖示<br>  if isRepeat {<br>    sender.setImage(UIImage(systemName: &quot;repeat.1&quot;), for: .normal)<br>  } else {<br>    sender.setImage(UIImage(systemName: &quot;repeat&quot;), for: .normal)<br>  }<br>}</pre><ul><li>建立重複播放事件（不改變現在播放的音樂index）</li></ul><pre>// 重複播放目前歌曲<br>func repeatSong () {<br>  changeSong()<br>}</pre><ul><li>放到自動下一首歌曲的事件中</li></ul><pre>override func viewDidLoad() {<br>// 當一首歌播完時<br>  NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil, queue: .main) { _ in<br>    if self.isRepeat {<br>      self.repeatSong()<br>    } else if !self.isRandom {<br>      self.nextSong()<br>    } else {<br>      self.randomSong()<br>    }<br>      self.playSong() <br>    }<br>}</pre><blockquote>github(選擇play-music分支)</blockquote><p><a href="https://github.com/hihiyuru/player/tree/play-music">GitHub - hihiyuru/player at play-music</a></p><blockquote>參考資料</blockquote><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%88%A9%E7%94%A8-viewdidload-%E9%BB%9E%E4%B8%80%E9%A6%96%E6%AD%8C-%E6%92%AD%E6%94%BE%E4%B8%80%E6%AC%A1pl-bfe59e9e22c">利用 AVPlayer 播放音樂音效</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-avplayerlooper-%E9%87%8D%E8%A6%86%E6%92%AD%E6%94%BE%E9%9F%B3%E6%A8%82%E5%92%8C%E5%BD%B1%E7%89%87-a9142d48465e">利用 AVPlayerLooper 重覆播放音樂和影片</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%AE%A2%E8%A3%BD-uikit-%E7%9A%84-uislider-%E6%A8%A3%E5%BC%8F-cee49b5038c0">客製 UIKit 的 UISlider 樣式</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/swift-4-2-%E6%9B%B4%E6%96%B9%E4%BE%BF%E7%9A%84%E4%BA%82%E6%95%B8-random-function-85fa69a08215">Swift 4.2 更方便的亂數 function，random，randomElement &amp; shuffle</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfa7a2f99109" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E4%BE%86%E5%AF%AB%E5%80%8B%E7%B0%A1%E5%96%AE%E7%9A%84%E9%9F%B3%E6%A8%82%E6%92%AD%E6%94%BE%E5%99%A8-%E4%B8%8B-bfa7a2f99109">來寫個簡單的音樂播放器（下）</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[來寫個簡單的音樂播放器（上）]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E4%BE%86%E5%AF%AB%E5%80%8B%E7%B0%A1%E5%96%AE%E7%9A%84%E9%9F%B3%E6%A8%82%E6%92%AD%E6%94%BE%E5%99%A8%E7%95%8C%E9%9D%A2-%E4%B8%8A-9f3230fd0934?source=rss-e51f6fabaff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f3230fd0934</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ibaction]]></category>
            <category><![CDATA[iboutlet]]></category>
            <dc:creator><![CDATA[Una]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 16:54:25 GMT</pubDate>
            <atom:updated>2023-07-27T10:35:00.430Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>這篇拉出畫面及能夠切換歌曲的功能是上集，下集在這裡</strong></blockquote><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/%E4%BE%86%E5%AF%AB%E5%80%8B%E7%B0%A1%E5%96%AE%E7%9A%84%E9%9F%B3%E6%A8%82%E6%92%AD%E6%94%BE%E5%99%A8-%E4%B8%8B-bfa7a2f99109">來寫個簡單的音樂播放器（下）</a></p><p>這次也是看著螢幕發呆好久，上完課都回憶不太起來自己怎麼寫出課堂範例的，然後坐在計時收費的自修室就會一臉呆滯，想到我的每分鐘都是錢才緩慢擠記憶</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*QBEbAo_WwYR1eqK1LtUsmw.gif" /></figure><p>Let’s Go!</p><blockquote><strong>操作畫面</strong></blockquote><p>目標是希望可以滑動歌曲封面切換歌曲，點擊分頁點點及上下首按鈕時，歌曲封面、名稱、歌詞都會隨切換變化，如果使用者切換到歌詞，換歌時也需要切回歌曲封面。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*Z0fV_UCFF6AigkVhaSbV6g.gif" /></figure><p><strong>1/建立專案並設計介面</strong></p><p>在Storyboard中設計音樂播放器介面，畫面中有一個UILabel顯示歌曲名稱、一個UILabel顯示歌手、一個UISegmentedControl切換專輯封面和歌詞視圖、一個UIImageView顯示專輯封面、一個UIScrollView顯示歌詞、一個UIPageControl顯示當前播放的歌曲，以及三個UIButton控制播放上一首、播放、播放下一首。我是參考Figma的設計圖拉出來的。</p><p>🌟特別說明：</p><ul><li>圖中會看到imageView跟scrollView元件重疊，這是因為我先把元件拉出來之後會利用程式碼控制哪個元件該消失哪個元件該出現。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*CzwlmGKogsM2Zuv0tipyPA.png" /></figure><ul><li>其中滑動的手勢會有兩個左右滑動，因此需要設定2個，但我還有歌詞滑動也可以切換，因此再加2個總共4個</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*GGb0GRZ6Ky8BSMfRKYpB8w.png" /><figcaption>歌詞手勢2個，封面照手勢2個</figcaption></figure><p>可參考資料：</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%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E9%96%8B%E7%99%BC-ios-app-%E7%9A%84-gesture-%E6%89%8B%E5%8B%A2%E5%8A%9F%E8%83%BD-uikit-%E7%89%88%E6%9C%AC-f6cb95075705">開發 iOS App 的 Gesture (手勢)功能 — UIKit 版本</a></li><li><a href="https://www.figma.com/community/file/1114645751180071469">High fidelity prototyping exercise - Music app | Figma Community</a></li><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/129-%E5%BE%9E-figma-community-%E7%B7%B4%E7%BF%92%E5%AF%A6%E4%BD%9C-app-%E7%95%AB%E9%9D%A2-cb7a1d774c56">#129 從 Figma Community 練習實作 App 畫面</a></li></ul><p>2/<strong>建立PlayerViewController類別</strong></p><p>此步驟可以直接看情歌王子的文章來實踐😇</p><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/%E6%96%B0%E5%A2%9E-cocoa-touch-class-%E7%9A%84%E6%AD%A5%E9%A9%9F%E8%AA%AA%E6%98%8E-5601a0b2ed3b">新增 Cocoa Touch Class 的步驟說明</a></p><p>3/<strong>@IBOutlet和@IBAction的使用</strong></p><p>@IBOutlet用於連結Storyboard中的元件到程式碼中的屬性，讓你可以在程式碼中操作這些元件。（像是web前端document.getElementById(&quot;XXX&quot;)）</p><p>@IBAction用於連結Storyboard中的元件到程式碼中的方法，讓你可以在使用者操作元件時執行相應的程式碼。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4yGqwzmhBV2_hgwBGt3Ag.png" /><figcaption>畫面中相關的@IBOutlet</figcaption></figure><p>現在，我們來解釋程式碼中的@IBOutlet和@IBAction的使用。</p><h4><strong>1.</strong>@IBOutlet</h4><p>在這個專案都用了以下這些如上圖對應區塊，這些@IBOutlet連結讓我們可以在程式碼中直接操作Storyboard中的對應元件，例如更改標籤(Label)的文字、設定圖片、顯示/隱藏視圖等等。</p><pre>@IBOutlet weak var titleLabel: UILabel!<br>@IBOutlet weak var singerLabel: UILabel!<br>@IBOutlet weak var songSegmentedControl: UISegmentedControl!<br>@IBOutlet weak var songPicImageView: UIImageView!<br>@IBOutlet weak var lyricsScrollView: UIScrollView!<br>@IBOutlet weak var lyricsLabel: UILabel!<br>@IBOutlet weak var songPageControl: UIPageControl!<br>@IBOutlet weak var playButton: UIButton!<br>@IBOutlet weak var preButton: UIButton!<br>@IBOutlet weak var nextButton: UIButton!</pre><h4>2. @IBAction</h4><p>此專案都用了以下這些方法使用了@IBOutlet，這些@IBAction連結讓我們可以在使用者操作Storyboard中的元件時，觸發相對應的方法，以執行我們想要的程式碼。例如，切換專輯封面和歌詞視圖、切換歌曲、滑動手勢等等。</p><pre>// 切換專輯封面視圖和歌詞視圖的IBAction<br>@IBAction func changeShow(_ sender: Any) {<br> // ...<br>}<br>    <br>// 切換歌曲的IBAction<br>@IBAction func changeSongPageControl(_ sender: Any) {<br>  // ...<br>}<br>    <br>// 滑動手勢事件<br>@IBAction func onSwiper(_ sender: Any) {<br>  // ...<br>}<br>    <br>// 上一首按鈕的IBAction<br>@IBAction func pre(_ sender: Any) {<br>  // ...<br>}<br><br>// 下一首按鈕的IBAction<br>@IBAction func next(_ sender: Any) {<br>  // ...<br>}</pre><p>4/<strong>設定連結及操作</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*l12YDgHr_8DAde_L3mL3zg.gif" /><figcaption>選擇每個需要連結的元件，按住Ctrl並拖曳到相對應的屬性上方</figcaption></figure><ol><li>連結@IBOutlet</li></ol><p>在Storyboard中，選擇每個需要連結的元件，按住Ctrl並拖曳到相對應的屬性上方，放開滑鼠時選擇連結的類型為Outlet，確定連結完成。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*ArblLFTxviOmX5tu2i66qw.png" /><figcaption>連結的類型為Outlet</figcaption></figure><p>2. 連結@IBAction</p><p>同樣地，在Storyboard中，選擇每個需要連結的元件，按住Ctrl並拖曳到相對應的方法上方，放開滑鼠時選擇連結的類型為Action，確定連結完成。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*T-wnvNzj8IH9SNemZJVcjg.png" /><figcaption>連結的類型為Action</figcaption></figure><p><strong>程式碼解說：</strong></p><ul><li>在viewDidLoad的時候希望在一開始渲染時就能拿到正確渲染第一首歌的資訊，因此有配置一些預設的程式碼：</li></ul><pre>override func viewDidLoad() {<br>  super.viewDidLoad()<br>        <br>  // 設定UIButton的配置<br>  var config = UIButton.Configuration.plain()<br>  // 設定圖像，將圖像顏色設定為白色並調整尺寸為64pt<br>  let resizedImage = UIImage(systemName: &quot;arrowtriangle.right.circle.fill&quot;)?.withTintColor(.white, renderingMode: .alwaysOriginal).resized(to: CGSize(width: 64, height: 64))<br>  config.image = resizedImage<br>        <br>  // 將配置應用到按鈕<br>  playButton.configuration = config<br>        <br>  // pageControl的點點<br>  songPageControl.numberOfPages = songName.count<br>        <br>  // 歌詞scrollView先隱藏<br>  lyricsScrollView.isHidden = true<br>  showingLyrics = false<br>        <br>  // 動態設定 Label 大小<br>  lyricsLabel.sizeToFit()<br>        <br>  // 初始化畫面<br>  changeSong()<br>}</pre><ul><li>再來會寫一些共用的方法，當點擊或滑動時就可以呼叫</li></ul><pre>// 切換至專輯封面視圖<br>func showSongPicView() {<br>  songPicImageView.isHidden = false<br>  lyricsScrollView.isHidden = true<br>  showingLyrics = false<br>}<br>    <br>// 切換至歌詞視圖<br>func showLyricsView() {<br>  songPicImageView.isHidden = true<br>  lyricsScrollView.isHidden = false<br>  showingLyrics = true<br>}<br>    <br>// 上一首歌曲<br>func preSong() {<br>  currentIndex = (currentIndex == 0) ? (songName.count - 1) : (currentIndex - 1)<br>  changeSong()<br>}<br>    <br>// 下一首歌曲<br>func nextSong() {<br>  currentIndex = (currentIndex == songName.count - 1) ? 0 : (currentIndex + 1)<br>  changeSong()<br>}<br>    <br>// 更新歌曲資訊及視圖顯示<br>func changeSong() {<br>  titleLabel.text = songName[currentIndex]<br>  singerLabel.text = singers[currentIndex]<br>  songPicImageView.image =  UIImage(named: albumsPic[currentIndex])<br>  songPageControl.currentPage = currentIndex<br>  lyricsLabel.text = &quot;\(songName[currentIndex])歌詞&quot;<br>  lyricsLabel.sizeToFit()<br>  songSegmentedControl.selectedSegmentIndex = 0<br>        <br>  // 根據showingLyrics的值，自動切換視圖<br>  showingLyrics = false<br>  if showingLyrics {<br>    showLyricsView()<br>  } else {<br>    showSongPicView()<br>  }<br>}</pre><ul><li>最後將@IBAction的邏輯寫好就大功告成了！</li></ul><pre>// 切換專輯封面視圖和歌詞視圖的IBAction<br>@IBAction func changeShow(_ sender: Any) {<br>  switch songSegmentedControl.selectedSegmentIndex {<br>    case 0:<br>      showSongPicView()<br>    case 1:<br>      showLyricsView()<br>    default:<br>      break<br>  }<br>}<br>    <br>// 切換歌曲的IBAction<br>@IBAction func changeSongPageControl(_ sender: Any) {<br>  currentIndex = songPageControl.currentPage<br>  changeSong()<br>}<br>    <br>// 滑動手勢事件<br>@IBAction func onSwiper(_ sender: Any) {<br>// 判斷滑動方向，並執行對應的上一首或下一首歌曲<br>  if let gestureRecognizer = sender as? UISwipeGestureRecognizer {<br>    if gestureRecognizer.direction == .left {<br>      nextSong()<br>    } else if gestureRecognizer.direction == .right {<br>      preSong()<br>    }<br>  }<br>}<br>    <br>// 上一首按鈕的IBAction<br>@IBAction func pre(_ sender: Any) {<br>  preSong()<br>}<br><br>// 下一首按鈕的IBAction<br>@IBAction func next(_ sender: Any) {<br>  nextSong()<br>}</pre><blockquote><strong>附上github（這集可以選分支ui-frame）</strong></blockquote><p><a href="https://github.com/hihiyuru/player/tree/ui-frame">GitHub - hihiyuru/player at ui-frame</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f3230fd0934" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E4%BE%86%E5%AF%AB%E5%80%8B%E7%B0%A1%E5%96%AE%E7%9A%84%E9%9F%B3%E6%A8%82%E6%92%AD%E6%94%BE%E5%99%A8%E7%95%8C%E9%9D%A2-%E4%B8%8A-9f3230fd0934">來寫個簡單的音樂播放器（上）</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[Swift中類（Class）、結構（Struct）、列舉（Enum）差異]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/swift%E4%B8%AD%E9%A1%9E-class-%E7%B5%90%E6%A7%8B-struct-%E5%88%97%E8%88%89-enum-%E5%B7%AE%E7%95%B0-8ef95d7747f2?source=rss-e51f6fabaff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ef95d7747f2</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Una]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 19:51:00 GMT</pubDate>
            <atom:updated>2023-07-22T03:45:31.411Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MYDcP6J6blzfhsUJmqtDNg.jpeg" /></figure><p>在前幾次練習swift時，有請AI幫忙優化程式碼，其中在課堂上學習了class因此當下就用了class當方法寫了，但AI優化過後是使用struct，因此開始了解他們之間的差異。</p><p>來吧，Let’s go!</p><h3>📍類（Class）</h3><ul><li>類是一種引用類型(reference type)。當你創建一個類的實例時，實際上是在內存中分配一塊空間來存儲該實例，並將變量指向該內存地址。多個變量可以引用同一個類的實例，這意味著它們共享同樣的數據。</li><li>類可以繼承自其他類，這允許你建立層次結構的類別。類的繼承可以重用父類的屬性和方法，並且還可以擴展和重寫它們。</li><li>類支持釋放機制，允許使用者手動管理內存。當所有引用都被解除，內存才會被釋放。</li></ul><p>🌟白話文：</p><pre>1.類就像是一個模版，可以用來創建不同類型的東西。<br>2.想像成一個製造玩具的工廠，工廠就是類，而玩具就是類的實例。每個工廠生產不同種類的玩具，就像類可以創建不同類型的實例。<br>3.類的特點是可以有很多屬性和方法，讓我們可以在裡面存儲和處理很多資訊。</pre><p>🌟用其他程式語言理解：</p><p>可以理解為javascript在new一個新的實例，當然概念上還是有些許不同。但可以先這樣理解。</p><pre>// Swift<br>// 在Swift中的類(class)是一種定義自定義型別的機制，用於創建物件。<br>// 當你定義一個類時，實際上是定義了一個新的型別，可以用來創建該類的實例。<br>// 當你想要使用該類來創建實例時，需要使用初始化器(init)來進行實例化。<br>class Person {<br>    var name: String<br>    var age: Int<br>    <br>    init(name: String, age: Int) {<br>        self.name = name<br>        self.age = age<br>    }<br>}<br><br>// 使用類的初始化器來創建實例<br>let person = Person(name: &quot;John&quot;, age: 30)<br>----------------------------------------------------------------<br>// JavaScript<br>// 在JavaScript中，new是用來創建物件的運算子。<br>// 當你有一個構造函數(constructor)時，使用new可以實例化一個新的物件。<br>class Person {<br>    constructor(name, age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br>}<br>// 使用new來創建物件實例<br>const person = new Person(&quot;John&quot;, 30);<br>----------------------------------------------------------------<br>在JavaScript中的構造函數（constructor）是用constructor關鍵字定義的，<br>而在Swift中是使用init初始化器。</pre><h3>📍結構（Struct）</h3><ul><li>結構是一種值類型(value type)。當你創建一個結構的實例時，實際上是在變量中存儲該實例的實際值，而不是引用。每個變量獨立存儲它們自己的數據，並且互不影響。</li><li>結構不支持繼承，這意味著結構不能從其他結構或類繼承屬性和方法。然而，你可以實現協議(protocol)以達到類似的功能。</li><li>結構在傳遞給函數或賦值給變量時是被複製的，這與類不同。這意味著當你修改一個結構的副本時，原始結構不會受到影響。</li></ul><p>🌟白話文：</p><pre>1.結構就像是一個小盒子，裡面可以放很多東西。<br>2.想像成一個魔法盒子，盒子裡面可以放不同種類的寶物，每個寶物是結構的一個實例。<br>3.結構的特點是每個實例都是獨立的，如果你改變了一個寶物，其他寶物不會受到影響。</pre><p>🌟用其他程式語言理解：</p><p>可以理解為typescript的interface，當然概念上還是有不同。特別注意struct的值都是獨立的 ; interface只定義物件的結構，值會因為指向同個物件而互相影響。</p><pre>// Swift<br>// Swift中的結構(struct)是一種值類型(value type)，用於定義包含多個屬性的型別。<br>// 它可以像類(class)一樣有屬性和方法，但它是值類型，表示每個變數都包含自己的值，而不是指向同一個內存位置。<br>// 當你將一個結構賦值給另一個變數或傳遞給函數時，它們是相互獨立的，修改一個變數的值不會影響到另一個變數。<br>struct Point {<br>    var x: Int<br>    var y: Int<br>}<br><br>var pointA = Point(x: 5, y: 10)<br>var pointB = pointA // 複製pointA的值給pointB<br><br>print(pointA.x, pointA.y) // 輸出：5 10<br>print(pointB.x, pointB.y) // 輸出：5 10<br><br>pointA.x = 7<br>print(pointA.x, pointA.y) // 輸出：7 10<br>print(pointB.x, pointB.y) // 輸出：5 10<br>----------------------------------------------------------------<br>// TypeScript<br>// 在TypeScript(TS)中的介面(interface)用於定義物件的結構，它只描述物件的形狀，而不實際創建物件。<br>// TS的介面並不是一個真正的值類型，它只是一個規範或約定，用於確保物件擁有特定的屬性和方法。<br>interface Point {<br>    x: number;<br>    y: number;<br>}<br><br>let pointA: Point = { x: 5, y: 10 };<br>let pointB: Point = pointA; // 複製pointA的參考給pointB<br><br>console.log(pointA.x, pointA.y); // 輸出：5 10<br>console.log(pointB.x, pointB.y); // 輸出：5 10<br><br>pointA.x = 7;<br>console.log(pointA.x, pointA.y); // 輸出：7 10<br>console.log(pointB.x, pointB.y); // 輸出：7 10<br>----------------------------------------------------------------<br>Swift的結構還具有值類型的特性，而TypeScript的介面僅僅是一個規範，並沒有值本身。</pre><h3>📍列舉（Enum）</h3><ul><li>列舉是一種特殊的值類型。它是一個定義了有限可能性的型別。每個可能的值稱為一個成員(member)。</li><li>列舉的成員可以是關聯值(associated values)，這使得列舉成員可以攜帶不同類型的相關數據。</li><li>列舉也可以有方法，讓你對列舉進行操作和處理。</li></ul><p>🌟白話文：</p><pre>1.列舉就像是一個有限的選擇，你只能從中選擇其中一個。<br>2.想像成一個口袋裡有不同種類的糖果，你只能選擇一種吃。每種糖果就是列舉的一個成員。<br>3.列舉的特點是它只有特定的幾個選項，你不能自己隨意添加。</pre><p>🌟使用場景：</p><pre>enum Direction {<br>    case up<br>    case down<br>    case left<br>    case right<br>}<br><br>// 創建一個Direction列舉的實例<br>let playerDirection = Direction.up<br><br>switch playerDirection {<br>case .up:<br>    print(&quot;Player is moving up&quot;)<br>case .down:<br>    print(&quot;Player is moving down&quot;)<br>case .left:<br>    print(&quot;Player is moving left&quot;)<br>case .right:<br>    print(&quot;Player is moving right&quot;)<br>}<br>// 輸出：Player is moving up</pre><blockquote>整理過後</blockquote><p>類（Class）：</p><ul><li>類就像是一個大家庭，裡面有很成員住在一起。每個成員都有自己的名字和年齡，還可以做各種各樣的事情。</li><li>你可以讓這個大家庭裡的每個人都知道同樣的事情，也可以讓他們一起做一些有趣的活動。</li></ul><p>結構（Struct）：</p><ul><li>結構就像是一個小房子，裡面只有一個人住。這個人有自己的名字和年齡，也可以做各種各樣的事情。</li><li>這個小房子裡的這個人可以做自己喜歡的事情，不用理會別的房子的人。</li></ul><p>總結：</p><ul><li>類就像是一個大家庭，裡面有很多人住在一起，他們可以一起做事情並分享資訊。</li><li>結構就像是一個小房子，裡面只有一個人住，他可以獨立做自己的事情，不用理會其他房子的人。</li><li>因為Class的Copy by Reference，因此不同的thread有可能同時在修改此物件中的變數，而使用struct就不必擔心會有此問題的出現。</li></ul><p>參考：</p><p><a href="https://ithelp.ithome.com.tw/articles/10200859">https://ithelp.ithome.com.tw/articles/10200859</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ef95d7747f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/swift%E4%B8%AD%E9%A1%9E-class-%E7%B5%90%E6%A7%8B-struct-%E5%88%97%E8%88%89-enum-%E5%B7%AE%E7%95%B0-8ef95d7747f2">Swift中類（Class）、結構（Struct）、列舉（Enum）差異</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[用 UIBezierPath 畫出低配版五條悟]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E7%94%A8-uibezierpath-%E7%95%AB%E5%87%BA%E4%BD%8E%E9%85%8D%E7%89%88%E4%BA%94%E6%A2%9D%E6%82%9F-f242de39d59f?source=rss-e51f6fabaff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f242de39d59f</guid>
            <category><![CDATA[uibezierpath]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Una]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 09:38:28 GMT</pubDate>
            <atom:updated>2023-07-21T08:14:17.351Z</atom:updated>
            <content:encoded><![CDATA[<p>原本覺得這個作業好像很好玩，沒想到花費好多時間，中途好幾次都想放棄，但頭都洗下去了，只好先寫出一個不太精緻的頭，就決定先暫停。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*pYKBGvxjnEM-OwOP31z22A.png" /><figcaption>對比照，沒有比較沒有傷害</figcaption></figure><blockquote>這次處理最久的就是眼鏡的漸層</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*6jeCKr_0mA03iAT--bYPrg.png" /></figure><p>是先使用了漸層的layer，然後將畫出來的鏡片變成mask達到效果，但是不知道為什麼，漸層的圖層x及y軸不是0,0就沒辦法成功顯示，如之後有得到解答再補充上來</p><pre>func addLeftGlasses() -&gt; CAGradientLayer {<br>    // 建立一個 UIBezierPath 來繪製眼鏡的左邊框形狀<br>    let path = UIBezierPath()<br>    path.move(to: CGPoint(x: 126, y: 295))<br>    path.addQuadCurve(to: CGPoint(x: 148, y: 275), controlPoint: CGPoint(x: 124, y: 282))<br>    path.addQuadCurve(to: CGPoint(x: 183, y: 285), controlPoint: CGPoint(x: 175, y: 269))<br>    path.addQuadCurve(to: CGPoint(x: 159, y: 309), controlPoint: CGPoint(x: 188, y: 300))<br>    path.addQuadCurve(to: CGPoint(x: 126, y: 296), controlPoint: CGPoint(x: 132, y: 313))<br>    path.close()<br>    <br>    // 建立一個 CAShapeLayer 來使用前面建立的 Bezier Path，並用於裁剪漸層圖層<br>    let leftGlassesLayer = CAShapeLayer()<br>    <br>    // 建立一個 CAGradientLayer 用於建立漸層效果<br>    let gradientLayer = CAGradientLayer()<br>    <br>    // 設定漸層圖層的尺寸為 (width: 800, height: 315)<br>    gradientLayer.frame = CGRect(x: 0, y: 0, width: 800, height: 315)<br>    <br>    // 將 Bezier Path 設定為裁剪漸層的遮罩<br>    leftGlassesLayer.path = path.cgPath<br>    <br>    // 設定漸層的顏色陣列，用於定義漸層的顏色變化<br>    gradientLayer.colors = [<br>        UIColor(cgColor: CGColor(red: 82/255, green: 107/255, blue: 152/255, alpha: 1)).cgColor,<br>        UIColor(cgColor: CGColor(red: 10/255, green: 37/255, blue: 61/255, alpha: 1)).cgColor,<br>        UIColor(cgColor: CGColor(red: 82/255, green: 107/255, blue: 152/255, alpha: 1)).cgColor,<br>        UIColor(cgColor: CGColor(red: 10/255, green: 37/255, blue: 61/255, alpha: 1)).cgColor<br>    ]<br>    <br>    // 設定漸層的位置，這決定了每個漸層色彩的分佈位置<br>    gradientLayer.locations = [0, 0.5, 0.9, 1]<br>    <br>    // 將裁剪圖層設定為漸層圖層的遮罩，以便僅在左邊框的形狀上顯示漸層效果<br>    gradientLayer.mask = leftGlassesLayer<br>    <br>    // 回傳建立完成的漸層圖層<br>    return gradientLayer<br>}</pre><blockquote>左邊的眼睫毛因為懶得再畫一次，所以也練習用CGAffineTransform處理</blockquote><pre>func addLeftEyelashes() -&gt; CAShapeLayer {<br>    // 右眼睫毛的path<br>    // ...<br>   <br>    <br>    // 創建 CAShapeLayer 來展示這個形狀<br>    let leftEyelashes = CAShapeLayer()<br>    // 將 UIBezierPath 轉換為 CGPath，並設定為 CAShapeLayer 的 path<br>    leftEyelashes.path = path.cgPath<br>    // 設定 CAShapeLayer 的 bounds 和 position 來決定圖層的位置和尺寸<br>    let boundingBox = path.cgPath.boundingBox<br>    leftEyelashes.bounds = boundingBox<br>    leftEyelashes.position = CGPoint(x: boundingBox.midX, y: boundingBox.midY)<br>    // 使用 CGAffineTransform 來進行旋轉和翻轉變換，讓左眼睫毛翻轉並旋轉成適合的位置<br>    let transform = CGAffineTransform(scaleX: -1, y: 1).translatedBy(x: 85, y: 20).rotated(by: -50)<br>    leftEyelashes.setAffineTransform(transform)<br>    // 設定填充色、邊框色和邊框寬度來控制圖形的外觀<br>    leftEyelashes.fillColor = UIColor(red: 169/255, green: 185/255, blue: 213/255, alpha: 1).cgColor<br>    leftEyelashes.strokeColor = CGColor(srgbRed: 35/255, green: 35/255, blue: 32/255, alpha: 1)<br>    leftEyelashes.lineWidth = 1<br>    <br>    // 回傳 CAShapeLayer 以供使用<br>    return leftEyelashes<br>}</pre><blockquote>附上github</blockquote><p><a href="https://github.com/hihiyuru/drawing">GitHub - hihiyuru/drawing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f242de39d59f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E7%94%A8-uibezierpath-%E7%95%AB%E5%87%BA%E4%BD%8E%E9%85%8D%E7%89%88%E4%BA%94%E6%A2%9D%E6%82%9F-f242de39d59f">用 UIBezierPath 畫出低配版五條悟</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[用ios SDK寫出一個emoji手機桌布吧]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E7%94%A8ios-sdk%E5%AF%AB%E5%87%BA%E4%B8%80%E5%80%8Bemoji%E6%89%8B%E6%A9%9F%E6%A1%8C%E5%B8%83%E5%90%A7-785eeec38024?source=rss-e51f6fabaff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/785eeec38024</guid>
            <category><![CDATA[playground]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Una]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 04:17:06 GMT</pubDate>
            <atom:updated>2023-07-18T04:40:43.047Z</atom:updated>
            <content:encoded><![CDATA[<p>ios16出來的時候有一個功能是emoji的桌布，覺得很可愛，可惜不能加上除了emoji的圖片，於是我們就自己來寫一個出來吧</p><p>Let’s go!</p><p><strong>1/第一個步驟是先把腦中想的畫面拆解出來，以下三個素材事先都先準備好，除了底圖的emoji排列，其餘都事先去背。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rFRn6uTreS8Tb5av-WX1kg.png" /><figcaption>先模擬了一下想要的emoji排列，以及準備好素材的圖片</figcaption></figure><p><strong>2/生成背景底圖</strong></p><pre>// 創建背景視圖<br>var rect = CGRect(x: 0, y: 0, width: 390, height: 844)<br>let bgView = UIView(frame: rect)<br>bgView.backgroundColor = UIColor(red: 117/255, green: 135/255, blue: 212/255, alpha: 1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*azA7T-u2JxO8gVtJrq86lw.png" /></figure><p><strong>3/生成emoji</strong></p><p>因為需要一個方法來計算一個圓圈的icon位置，所以寫一個共用方法createIcons，讓之後每圈的icon都能利用這個方法計算出位置。</p><pre>// 創建一個表示icon的座標及符號的結構<br>struct Icon {<br>    var x: Double<br>    var y: Double<br>    var symbol: String<br>}<br><br>// 函式：計算icon座標<br>func createIcons(centerX: Double, centerY: Double, radius: Double, numIcons: Int, symbol: String) -&gt; [Icon] {<br>    // 儲存計算出的icon座標的陣列<br>    var icons = [Icon]()<br>    // 迴圈計算每個icon的座標<br>    for i in 0..&lt;numIcons {<br>        // 計算θ（theta）的值，θ表示每個icon在圓上的位置，以弧度為單位<br>        let theta = (2.0 * Double.pi * Double(i)) / Double(numIcons)<br>        // 計算icon的x和y座標<br>        let x = centerX + radius * cos(theta)<br>        let y = centerY + radius * sin(theta)<br>         // 將icon的座標及符號儲存到icons陣列中<br>        icons.append(Icon(x: x, y: y, symbol: symbol))<br>    }<br>    // 回傳儲存所有icon座標的陣列<br>    return icons<br>}</pre><p>每一個圈的icon都設置相關的數值，在呼叫上述的方法跑出icon</p><pre>/**<br> * @param {Double} bones_radius - 骨頭icon圓圈半徑<br> * @param {Int} bones_num_icons - 骨頭icon數量<br> * @param {[Icon]} bones_icon_positions - 骨頭icon座標位置，及圖示<br> */<br>let bones_radius = 300.0<br>let bones_num_icons = 30<br>let bones_icon_positions = createIcons(centerX: center_x, centerY: center_y, radius: bones_radius, numIcons: bones_num_icons, symbol: &quot;🦴&quot;)<br>for (index, icon) in bones_icon_positions.enumerated() {<br>    print(&quot;Icon \(index + 1): x = \(icon.x), y = \(icon.y)&quot;)<br>    // 創建並設定骨頭icon的UILabel<br>    let iconLabel = UILabel(frame: CGRect(x: icon.x, y: icon.y, width: 50, height: 50))<br>    iconLabel.text = icon.symbol<br>    iconLabel.font = UIFont.systemFont(ofSize: 50)<br>    bgView.addSubview(iconLabel)<br>}<br><br>/**<br> * @param {Double} bear_radius - 熊icon圓圈半徑<br> * @param {Int} bear_num_icons - 熊icon數量<br> * @param {[Icon]} bear_icon_positions - 熊icon座標位置，及圖示<br> */<br>let bear_radius = 230.0<br>let bear_num_icons = 20<br>let bear_icon_positions = createIcons(centerX: center_x, centerY: center_y, radius: bear_radius, numIcons: bear_num_icons, symbol: &quot;🧸&quot;)<br>for (index, icon) in bear_icon_positions.enumerated() {<br>    print(&quot;Icon \(index + 1): x = \(icon.x), y = \(icon.y)&quot;)<br>    // 創建並設定熊icon的UILabel<br>    let iconLabel = UILabel(frame: CGRect(x: icon.x, y: icon.y, width: 50, height: 50))<br>    iconLabel.text = icon.symbol<br>    iconLabel.font = UIFont.systemFont(ofSize: 50)<br>    bgView.addSubview(iconLabel)<br>}<br><br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*hANqBcW_ymBR5K74r13u4g.png" /></figure><p><strong>5/疊加剩餘的兩張圖，就完成啦</strong></p><pre>// 增加MGM外框圖片<br>let MGMImage = UIImage(named: &quot;MGM.png&quot;)<br>let MGMImgaeView = UIImageView(image: MGMImage)<br>MGMImgaeView.frame = CGRect(x: -50, y: 260, width: 490, height: 300)<br>MGMImgaeView.contentMode = .scaleAspectFill<br>bgView.addSubview(MGMImgaeView)<br><br>// 增加狗的圖片<br>let dogImage = UIImage(named: &quot;dog.png&quot;)<br>let dogImgaeView = UIImageView(image: dogImage)<br>dogImgaeView.frame = CGRect(x: 135, y: 330, width: 100, height: 150)<br>dogImgaeView.contentMode = .scaleAspectFill<br>bgView.addSubview(dogImgaeView)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*EXT_PsBRSmkD73f88-064Q.jpeg" /></figure><blockquote><strong>完整程式碼</strong></blockquote><pre>// 匯入UIKit框架，用於創建UI元素<br>import UIKit<br>// 匯入Foundation框架，提供一些基本功能<br>import Foundation<br>// 匯入PlaygroundSupport框架，使Playground可以渲染視圖<br>import PlaygroundSupport<br><br>// 創建一個表示icon的座標及符號的結構<br>struct Icon {<br>    var x: Double<br>    var y: Double<br>    var symbol: String<br>}<br><br>// 函式：計算icon座標<br>func createIcons(centerX: Double, centerY: Double, radius: Double, numIcons: Int, symbol: String) -&gt; [Icon] {<br>    // 儲存計算出的icon座標的陣列<br>    var icons = [Icon]()<br>    // 迭代計算每個icon的座標<br>    for i in 0..&lt;numIcons {<br>        // 計算θ（theta）的值，θ表示每個icon在圓上的位置，以弧度為單位<br>        let theta = (2.0 * Double.pi * Double(i)) / Double(numIcons)<br>        // 計算icon的x和y座標<br>        let x = centerX + radius * cos(theta)<br>        let y = centerY + radius * sin(theta)<br>        // 將icon的座標及符號儲存到icons陣列中<br>        icons.append(Icon(x: x, y: y, symbol: symbol))<br>    }<br>    // 回傳儲存所有icon座標的陣列<br>    return icons<br>}<br><br>// 創建背景視圖<br>var rect = CGRect(x: 0, y: 0, width: 390, height: 844)<br>let bgView = UIView(frame: rect)<br>// 設定背景視圖的背景顏色<br>bgView.backgroundColor = UIColor(red: 117/255, green: 135/255, blue: 212/255, alpha: 1)<br><br>// 圓心的座標<br>let center_x = 170.0<br>let center_y = 400.0<br><br>// 處理太陽icon<br>let sun_radius = 380.0<br>let sun_num_icons = 25<br>// 使用createIcons函式計算太陽icon的座標<br>let sun_icon_positions = createIcons(centerX: center_x, centerY: center_y, radius: sun_radius, numIcons: sun_num_icons, symbol: &quot;🔆&quot;)<br>for (index, icon) in sun_icon_positions.enumerated() {<br>    // 印出太陽icon的座標資訊<br>    print(&quot;Icon \(index + 1): x = \(icon.x), y = \(icon.y)&quot;)<br>    // 創建並設定太陽icon的UILabel<br>    let iconLabel = UILabel(frame: CGRect(x: icon.x, y: icon.y, width: 50, height: 50))<br>    iconLabel.text = icon.symbol<br>    iconLabel.font = UIFont.systemFont(ofSize: 50)<br>    bgView.addSubview(iconLabel)<br>}<br><br>// 處理骨頭icon<br>let bones_radius = 300.0<br>let bones_num_icons = 30<br>// 使用createIcons函式計算骨頭icon的座標<br>let bones_icon_positions = createIcons(centerX: center_x, centerY: center_y, radius: bones_radius, numIcons: bones_num_icons, symbol: &quot;🦴&quot;)<br>for (index, icon) in bones_icon_positions.enumerated() {<br>    // 印出骨頭icon的座標資訊<br>    print(&quot;Icon \(index + 1): x = \(icon.x), y = \(icon.y)&quot;)<br>    // 創建並設定骨頭icon的UILabel<br>    let iconLabel = UILabel(frame: CGRect(x: icon.x, y: icon.y, width: 50, height: 50))<br>    iconLabel.text = icon.symbol<br>    iconLabel.font = UIFont.systemFont(ofSize: 50)<br>    bgView.addSubview(iconLabel)<br>}<br><br>// 處理熊icon<br>let bear_radius = 230.0<br>let bear_num_icons = 20<br>// 使用createIcons函式計算熊icon的座標<br>let bear_icon_positions = createIcons(centerX: center_x, centerY: center_y, radius: bear_radius, numIcons: bear_num_icons, symbol: &quot;🧸&quot;)<br>for (index, icon) in bear_icon_positions.enumerated() {<br>    // 印出熊icon的座標資訊<br>    print(&quot;Icon \(index + 1): x = \(icon.x), y = \(icon.y)&quot;)<br>    // 創建並設定熊icon的UILabel<br>    let iconLabel = UILabel(frame: CGRect(x: icon.x, y: icon.y, width: 50, height: 50))<br>    iconLabel.text = icon.symbol<br>    iconLabel.font = UIFont.systemFont(ofSize: 50)<br>    bgView.addSubview(iconLabel)<br>}<br><br>// 處理星星icon<br>let star_radius = 150.0<br>let star_num_icons = 15<br>// 使用createIcons函式計算星星icon的座標<br>let star_icon_positions = createIcons(centerX: center_x, centerY: center_y, radius: star_radius, numIcons: star_num_icons, symbol: &quot;🌟&quot;)<br>for (index, icon) in star_icon_positions.enumerated() {<br>    // 印出星星icon的座標資訊<br>    print(&quot;Icon \(index + 1): x = \(icon.x), y = \(icon.y)&quot;)<br>    // 創建並設定星星icon的UILabel<br>    let iconLabel = UILabel(frame: CGRect(x: icon.x, y: icon.y, width: 50, height: 50))<br>    iconLabel.text = icon.symbol<br>    iconLabel.font = UIFont.systemFont(ofSize: 50)<br>    bgView.addSubview(iconLabel)<br>}<br><br>// 增加MGM外框圖片<br>let MGMImage = UIImage(named: &quot;MGM.png&quot;)<br>let MGMImgaeView = UIImageView(image: MGMImage)<br>MGMImgaeView.frame = CGRect(x: -50, y: 260, width, height: 490) // 設定MGM外框圖片的位置及大小<br>MGMImgaeView.contentMode = .scaleAspectFill // 設定圖片填充模式為等比例填充<br>bgView.addSubview(MGMImgaeView) // 將MGM外誆圖片添加到背景視圖中<br><br>// 增加狗的圖片<br>let dogImage = UIImage(named: &quot;dog.png&quot;)<br>let dogImgaeView = UIImageView(image: dogImage)<br>dogImgaeView.frame = CGRect(x: 135, y: 330, width: 100, height: 150) // 設定狗的圖片位置及大小<br>dogImgaeView.contentMode = .scaleAspectFill // 設定圖片填充模式為等比例填充<br>bgView.addSubview(dogImgaeView) // 將狗的圖片添加到背景視圖中<br><br>bgView // 顯示背景視圖<br>PlaygroundPage.current.liveView = bgView // 將背景視圖設定為Playground的即時預覽視圖</pre><blockquote>完成圖</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*jVKsJZXVuTpIilK6czwqMw.png" /><figcaption>換成桌布囉～</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=785eeec38024" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E7%94%A8ios-sdk%E5%AF%AB%E5%87%BA%E4%B8%80%E5%80%8Bemoji%E6%89%8B%E6%A9%9F%E6%A1%8C%E5%B8%83%E5%90%A7-785eeec38024">用ios SDK寫出一個emoji手機桌布吧</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[不寫程式，拉出一個電子書app]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E4%B8%8D%E5%AF%AB%E7%A8%8B%E5%BC%8F-%E6%8B%89%E5%87%BA%E4%B8%80%E5%80%8B%E9%9B%BB%E5%AD%90%E6%9B%B8app-be584cae66fd?source=rss-e51f6fabaff8------2</link>
            <guid isPermaLink="false">https://medium.com/p/be584cae66fd</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[storyboard]]></category>
            <dc:creator><![CDATA[Una]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 13:15:08 GMT</pubDate>
            <atom:updated>2023-07-13T14:54:25.955Z</atom:updated>
            <content:encoded><![CDATA[<p>這次使用storyboard拉出一個電子書app，雖然已百年沒用adobe illustrator，但依舊有一種當年在操作adobe illustrator的既視感，好幾次都想把圖層鎖起來，移動位置的時候真的好崩潰இдஇ，用mac巧控板拉畫面，拉到最後手都在抖இдஇ</p><p>好啦現在就開始交作業吧！Let’s go！</p><p>介紹此次有使用到的功能選手</p><ul><li>tab bar controller &amp; navigation controller</li><li>table view controller with static cells</li><li>scroll View</li><li>view，button，label，image view，table view，scroll view，visual effect view with blur，tap gesture recognizer。</li></ul><p>操作畫面：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*_X8n1NcaYFdmozgOyLwcBw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*BaIySRwydfp-yUCFhPyp_g.jpeg" /><figcaption>storybroad所有畫面</figcaption></figure><h4>📍 主頁:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*vDeIiJr9BzrNdLruHpYS5w.gif" /></figure><ul><li>在起始頁中使用了scroll view來做熱門專輯排行，其中要注意的就是需要在scroll view中設置contentSize，因為是左右滑動所以只需要填寫花括弧中的第一個欄位，第二個欄位則為0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*uxtYuOyxfAMcrgCWjfbKng.png" /></figure><p>可參閱：</p><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%9C%A8-storyboard-%E8%A8%AD%E5%AE%9A-content-size-%E5%AF%A6%E7%8F%BE%E6%B0%B4%E5%B9%B3%E6%8D%B2%E5%8B%95%E7%9A%84-scroll-view-2710fa247293">設定 content size，實現水平捲動，上下捲動和分頁的 scroll view</a></p><ul><li>熱門專輯的每個item是先使用了view將畫面做好，再疊加上tap gesture recognizer手勢作為按鈕使用</li></ul><h4>📍 故事內容頁:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*cmCe73903nMFCRbpShf7Jw.gif" /></figure><ul><li>說個題外話，原本在這裡想使用ai的幫助來產一個故事，但沒想到比想像中難，看來還沒辦法成為ai咒術師，最後用了<a href="https://blog.elielin.com/20167">IGT偵探趣味</a>產出的可愛童書作為作業練習的故事。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dr-bnOHyNBOlUl3GSl9jBA.png" /><figcaption>使用leonardo.ai產出來的圖，但風格無法一致</figcaption></figure><ul><li>因為想讓使用者不用侷限點擊button所以也是使用了tap gesture recognizer手勢來換到下一頁。</li></ul><h4>📍 故事專輯簡介:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*ghA9OjquOeH529Jhm7DH3g.gif" /></figure><ul><li>在專輯圖片中可以一格一格切換換圖片也是使用scroll view不同的是，這次需要將paging Enbled勾選起來達到此效果</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*3FQ2jk4r1Jryunt-QCF-3g.png" /></figure><ul><li>內容簡介的部分,因為是滑動y軸，因此contentSize只需要設置第二個參數</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*CC-743LADCpHplQgSSwlNQ.png" /></figure><h4>📍 書櫃頁面:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*g9djwC8YPBUSMEkH6zxcnQ.gif" /></figure><ul><li>使用table view controller，其中要注意的是因為目前表單是靜態資料，因此table view需要改為static cells：</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*wjW7bUa-Chp7Zh1PbrMJgg.png" /></figure><h4>📍 遇到其他的問題:</h4><ul><li>navigation bar如何維持同一個樣式，不受捲動時影響，解決方法如下：</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*aZeXlk_N94Zq23NpC_VvGg.png" /></figure><p>可參閱：</p><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-15-navigation-bar-tab-bar-%E7%9A%84%E6%A8%A3%E5%BC%8F%E8%A8%AD%E5%AE%9A-558f07137b52">iOS 15 navigation bar &amp; tab bar 的樣式設定(appearance)</a></p><h4>📍附上作品github：</h4><p><a href="https://github.com/hihiyuru/ebook">GitHub - hihiyuru/ebook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be584cae66fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E4%B8%8D%E5%AF%AB%E7%A8%8B%E5%BC%8F-%E6%8B%89%E5%87%BA%E4%B8%80%E5%80%8B%E9%9B%BB%E5%AD%90%E6%9B%B8app-be584cae66fd">不寫程式，拉出一個電子書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>
    </channel>
</rss>