<?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 Julia on Medium]]></title>
        <description><![CDATA[Stories by Julia on Medium]]></description>
        <link>https://medium.com/@juliaxiao860508?source=rss-3448c313725b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nMsVi_OpG9qGv_GmbdOVRw.jpeg</url>
            <title>Stories by Julia on Medium</title>
            <link>https://medium.com/@juliaxiao860508?source=rss-3448c313725b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 18:08:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@juliaxiao860508/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 / Part6. 從 cocoapods 安裝套件來製作 sidemenu 和 寫數學公式]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part6-%E5%BE%9E-cocoapods-%E5%AE%89%E8%A3%9D%E5%A5%97%E4%BB%B6%E4%BE%86%E8%A3%BD%E4%BD%9C-sidemenu-%E5%92%8C-%E5%AF%AB%E6%95%B8%E5%AD%B8%E5%85%AC%E5%BC%8F-136ef00f2a23?source=rss-3448c313725b------2</link>
            <guid isPermaLink="false">https://medium.com/p/136ef00f2a23</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Julia]]></dc:creator>
            <pubDate>Tue, 05 Apr 2022 06:45:25 GMT</pubDate>
            <atom:updated>2022-04-05T13:50:34.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*kUDpsDEIQUVVnBtzfxHorA.gif" /></figure><h3>安裝 cocoapods 和想要的 package</h3><ol><li>打開 terminal 輸入下面的程式 (只在第一 download 需要）</li></ol><pre>sudo gem install cocoapods</pre><p>2. 在 terminal cd 打開 xcode project</p><pre>cd Desktop/stockTracker</pre><p>3. 創一個 Podfile並打開它</p><pre>pod init<br>ls<br>open Podfile</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*LeNi_rRgF0trc6LpzULaYw.png" /></figure><p>4. 在 termimal 安裝</p><pre>pod install</pre><p>5. 打開 xcode project 確認 Pods 檔案有沒有生成</p><pre>ls<br>open stockTracker.xcworkspace/</pre><h3>製作 sideMenu</h3><ol><li>從 cocoapods import SideMenu</li></ol><p>2. 在想要的 controller 加入 SideMenu</p><pre>import SideMenu<br>var sideMenu : SideMenuNavigationController?<br><br>override func viewDidLoad() {<br>    super.viewDidLoad()</pre><pre>    // sidemenu setting <br>    // 等等幫 sidemenu 做一個 tableView，先把它設為 rootViewController<br>    sideMenu = SideMenuNavigationController(rootViewController: sideMenuTableViewController())</pre><pre>    // 讓sidemuenu 靠左<br>    sideMenu?.leftSide = true<br>        <br>    // 加入往左滑可以得到 sidemenu 的手勢 SideMenuManager.default.leftMenuNavigationController = sideMenu<br>    SideMenuManager.default.addPanGestureToPresent(toView: self.view)   <br>}</pre><p>3. 為 sidemenu 製作一個 tableViewController</p><ul><li>用 didSelectRowAt function 將使用者倒到想要的頁面</li></ul><pre>import UIKit</pre><pre>class sideMenuTableViewController: UITableViewController {<br>    <br>    let contentList = [&quot;Definition&quot;]</pre><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        tableView.register(UITableViewCell.self, forCellReuseIdentifier: &quot;sideMenuTableViewCell&quot;)<br>        tableView.separatorStyle = .singleLine<br>        tableView.separatorColor = .lightGray<br>        tableView.backgroundColor = .darkGray</pre><pre>}</pre><pre>// MARK: - Table view data source</pre><pre>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        <br>        return contentList.count<br>    }</pre><pre>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;sideMenuTableViewCell&quot;, for: indexPath)<br>        var content = cell.defaultContentConfiguration()<br>        content.text = contentList[indexPath.row]<br>        content.textProperties.color = .white<br>        cell.contentConfiguration = content<br>        cell.selectionStyle = .none<br>        cell.backgroundColor = .darkGray</pre><pre>return cell<br>    }<br>    <br>    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>        if indexPath.row == 0{<br>            <br>            <br>            guard let controller =<br>                    UIStoryboard(name: &quot;Main&quot;, bundle: .main).instantiateViewController(withIdentifier: &quot;definitionViewController&quot;) as? definitionViewController else {<br>                print(&quot;fail&quot;)<br>                return }<br>            <br>            present(controller, animated: true, completion: nil)<br>            <br>        }<br>    }<br>    <br>}</pre><p>下面有詳細的教學可以參考喔</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fiq-tWW45Vhk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Diq-tWW45Vhk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fiq-tWW45Vhk%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/ebdf367e988515ccf8f56e8d3c744f02/href">https://medium.com/media/ebdf367e988515ccf8f56e8d3c744f02/href</a></iframe><h3>import iosMath 寫美麗的數學公式</h3><ol><li>從 cocoapods 安裝 iosMath 後</li><li>在 StoryBoard 拉一個 view 並把 class 改成 MTMathUILabel</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*RXpsNaUrvH1aAzqoc4sY7g.png" /></figure><p>3. 像編輯 Latex 一樣編輯 formula</p><ul><li>跳下一行 ：\\\\</li><li>在每一個數學 function 之前加 \\</li></ul><pre>import iosMath<br>avgDollarCostMathLabel.latex = &quot;Amount = price \\times shares \\\\  \\text{Average Dollar Cost} = \\frac{\\sum_{i=1}^N Amount_i}{\\text{Number of Shares}} &quot;</pre><p>下面有官方範例教學喔</p><p><a href="https://github.com/kostub/iosMath/blob/master/EXAMPLES.md">iosMath/EXAMPLES.md at master · kostub/iosMath</a></p><h3>Github:</h3><p><a href="https://github.com/Luca0508/stockTracker">GitHub - Luca0508/stockTracker</a></p><h3>Link：</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part1-watch-list-3205d7fd764f">美股記帳 App / Part1. Watch List</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-2-coredata-nsfetchedresultscontroller-%E5%AD%98%E5%8F%96%E8%B3%87%E6%96%99-ce5418fa95a">美股記帳 App / Part 2. CoreData &amp; NSFetchedResultsController 存取資料</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-3-%E5%9D%87%E5%83%B9%E7%8D%B2%E5%88%A9%E8%A8%88%E7%AE%97-charts-%E8%A3%BD%E4%BD%9C%E5%9C%96%E8%A1%A8%E5%88%86%E6%9E%90-b739d3e53ad7">美股記帳 App / Part 3 均價獲利計算 &amp; Charts 製作圖表分析</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-4-websocket-%E6%8A%93stock-real-time-price-e0d965711ee0">美股記帳 App / Part 4. Websocket 抓stock real time price</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-5-%E5%B0%8E%E5%85%A5-csv-%E6%AA%94-da404d97cd22">美股記帳 App / Part 5. 導入 .csv 檔</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=136ef00f2a23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part6-%E5%BE%9E-cocoapods-%E5%AE%89%E8%A3%9D%E5%A5%97%E4%BB%B6%E4%BE%86%E8%A3%BD%E4%BD%9C-sidemenu-%E5%92%8C-%E5%AF%AB%E6%95%B8%E5%AD%B8%E5%85%AC%E5%BC%8F-136ef00f2a23">美股記帳 App / Part6. 從 cocoapods 安裝套件來製作 sidemenu 和 寫數學公式</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 / Part 5. 導入 .csv 檔]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-5-%E5%B0%8E%E5%85%A5-csv-%E6%AA%94-da404d97cd22?source=rss-3448c313725b------2</link>
            <guid isPermaLink="false">https://medium.com/p/da404d97cd22</guid>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Julia]]></dc:creator>
            <pubDate>Sat, 02 Apr 2022 10:58:00 GMT</pubDate>
            <atom:updated>2022-04-05T06:49:56.861Z</atom:updated>
            <content:encoded><![CDATA[<h3>美股記帳 App / Part 5. 導入 .csv 檔</h3><p>懶得手動輸入交易嗎？害怕不小心把交易輸入錯誤嗎？</p><p>現在只要從券商那裡下載交易明細，按照指示簡單修改一下，就可以直接導入.csv 檔，將交易加進 App 喔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*0uTRgxTQl_FG5ceF69uagA.gif" /></figure><h3>安裝 CHCSVParser</h3><ul><li>首先，先下載下面 github 裡的檔案，並把 .h 和 .m 的檔案拉進 xcode 的 project 裡</li></ul><p><a href="https://github.com/davedelong/CHCSVParser">GitHub - davedelong/CHCSVParser: A proper CSV parser for Objective-C</a></p><ul><li>因為檔案是 objective-c 語言，所以加進去的時候會問你要不要加個 bridge，選擇要，並加入下面程式</li></ul><pre>#import &quot;CHCSVParser.h&quot;</pre><h3>從手機裡選擇檔案</h3><ul><li>使用 UIDocumentPickerViewController 來選曲檔案</li></ul><pre><a href="http://twitter.com/IBAction">@IBAction</a> func importFile(_ sender: Any) {<br>        <br>        let supportedFile : [UTType] = [UTType.data]<br>        <br>        let DocumentPickerController = UIDocumentPickerViewController(forOpeningContentTypes: supportedFile, asCopy: true)<br>        DocumentPickerController.delegate = self<br>        DocumentPickerController.allowsMultipleSelection = false<br>    <br>        present(DocumentPickerController, animated: true, completion: nil)<br>    }</pre><h3>讀取 .csv 檔</h3><ul><li>先建一個 讀取 csv 的 struct，並依 header 設定 init</li></ul><pre>struct importFile : Codable{<br>    var dateString : String<br>    var description : String<br>   <br>    init(raw:[String]) {<br>        dateString = raw[0]<br>        description = raw[1]<br>    }  <br>}</pre><ul><li>讀取 csv 檔裡的資料並檔入前面建的 struct</li><li>在讀檔錯誤的時候，跳出警告並告知 csv 檔裡的哪一行出現錯誤，方便使用者修改</li><li>在讀檔正確的時候，也跳出提示使用者</li></ul><pre>func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {<br>        print(&quot;file was selected&quot;)<br>        <strong>var</strong> correctFormat = <strong>true</strong></pre><pre>        let rows = NSArray(contentsOfCSVURL: url, options:CHCSVParserOptions.sanitizesFields)!</pre><pre><br>        for (index, rowContent) in rows.enumerated(){<br>            if index != 0, let rowString = rowContent as? [String]{<br>                let importFileStruct = stockTracker.importFile.init(raw:rowString)<br><br>            }else{<br>                    correctFormat = false<br>                    <br>                    let alertController = UIAlertController(title: &quot;Warning!!!&quot;, message: &quot;The format of imported .csv file may be wrong.(error in line : \(index) of the imported file). Please follow the instruction below&quot;, preferredStyle: .alert)<br>                    alertController.addAction(UIAlertAction(title: &quot;OK&quot;, style: .default, handler: nil))<br>                    present(alertController, animated: true, completion: nil)<br>                    <br>                    break<br>                }<br>                <br>            }<br>        }<br>        <br>        if correctFormat{<br>                       <br>            let alertController = UIAlertController(title: &quot;Message&quot;, message: &quot;Import the File Successfully!!! Please check them in Transaction Report.&quot;, preferredStyle: .alert)<br>            alertController.addAction(UIAlertAction(title: &quot;OK&quot;, style: .default))<br>            present(alertController, animated: true, completion: nil)<br>            <br>        }else {<br>            print(&quot;the format of imported file is incorrect&quot;)<br>        }<br>    }<br>}</pre><p>詳情可以參考下面的 youtube 教學，教的很詳細喔！！</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fg7KdnWICA7Q%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dg7KdnWICA7Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fg7KdnWICA7Q%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/fdfc8cda1b14b73c5e885a1a60f2410c/href">https://medium.com/media/fdfc8cda1b14b73c5e885a1a60f2410c/href</a></iframe><h3>Github:</h3><p><a href="https://github.com/Luca0508/stockTracker">GitHub - Luca0508/stockTracker</a></p><h3>Link:</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part1-watch-list-3205d7fd764f">美股記帳 App / Part1. Watch List</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-2-coredata-nsfetchedresultscontroller-%E5%AD%98%E5%8F%96%E8%B3%87%E6%96%99-ce5418fa95a">美股記帳 App / Part 2. CoreData &amp; NSFetchedResultsController 存取資料</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-3-%E5%9D%87%E5%83%B9%E7%8D%B2%E5%88%A9%E8%A8%88%E7%AE%97-charts-%E8%A3%BD%E4%BD%9C%E5%9C%96%E8%A1%A8%E5%88%86%E6%9E%90-b739d3e53ad7">美股記帳 App / Part 3 均價獲利計算 &amp; Charts 製作圖表分析</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-4-websocket-%E6%8A%93stock-real-time-price-e0d965711ee0">美股記帳 App / Part 4. Websocket 抓stock real time price</a></li><li><a href="https://medium.com/@juliaxiao860508/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part6-%E5%BE%9E-cocoapods-%E5%AE%89%E8%A3%9D%E5%A5%97%E4%BB%B6%E4%BE%86%E8%A3%BD%E4%BD%9C-sidemenu-%E5%92%8C-%E5%AF%AB%E6%95%B8%E5%AD%B8%E5%85%AC%E5%BC%8F-136ef00f2a23">美股記帳 App / Part6. 從 cocoapods 安裝套件來製作 sidemenu 和 寫數學公式</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da404d97cd22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-5-%E5%B0%8E%E5%85%A5-csv-%E6%AA%94-da404d97cd22">美股記帳 App / Part 5. 導入 .csv 檔</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 / Part 4. Websocket 抓stock real time price]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-4-websocket-%E6%8A%93stock-real-time-price-e0d965711ee0?source=rss-3448c313725b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0d965711ee0</guid>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Julia]]></dc:creator>
            <pubDate>Mon, 21 Mar 2022 16:47:49 GMT</pubDate>
            <atom:updated>2022-04-02T10:58:55.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*elqHkHurol9GjEw4NJIOVg.gif" /></figure><h3>Websocket</h3><ul><li>只要 shakeHand 成功過後，兩者就可以，兩者就可以持久性的連接，並且能雙向傳遞資料，不用一直 get post</li><li>Finnhub 提供了用 websocket 連線的 Last Price Updates，比在 <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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part1-watch-list-3205d7fd764f">watchList</a> 裡取得的股價資訊更即時，但提供的資訊更即時，但提供的資訊比較少，因此決定將即時的價格放在各個股票的頁面</li></ul><p><a href="https://finnhub.io/docs/api/websocket-trades">Finnhub - Free realtime APIs for stock, forex and cryptocurrency.</a></p><h4>建立 WebSocket</h4><ol><li>遵從 URLSessionWebSocketDelegate</li><li>建立取得資料的 struct，等一下用 JSONEncoder 得到資料</li></ol><pre>struct websocketStockInfo : Codable{<br>    var type : String<br>    var data : [priceData]<br>}</pre><pre>struct priceData : Codable{<br>    var s : String // symbol<br>    var p : Double // price<br>}</pre><ul><li>func setSession() ：開啟連線</li><li>func ping() ：確保連線正常，並回傳一個pong</li><li>func send() ：送字串訊息過去，讓他知道你要什麼</li><li>func receive()：收到 result type 的訊息，在 string的結過裡解 json 並把得到的價格 update 到 label 裡</li><li>func close : 中斷連線</li><li><strong>func</strong> urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) ：當 websocket 連線成功後 依序啟動 ping send receive function</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fc4ae50b5ba415a670269c3b8049eb2/href">https://medium.com/media/8fc4ae50b5ba415a670269c3b8049eb2/href</a></iframe><h4>判斷股票市場開市了沒</h4><p>使用 websocket 所得到的價格資訊，只有在美股開市的時候才有，所以在不是開市的時間，我會用 https api (<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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part1-watch-list-3205d7fd764f">watch List</a> 裡的方法)取的價格資訊</p><ul><li>美股開市時間 ：紐約時間週一到週五的早上九點半到下午四點</li><li>記得 now variable 裡 取的時間也要是紐約時間</li><li>用 NSCalandar ().isDateInWeekend 判斷是不是週末</li></ul><pre>let newYorkTimeZone = TimeZone(identifier: &quot;America/New_York&quot;)!</pre><pre>let now = Date().addingTimeInterval(TimeInterval.init(newYorkTimeZone.secondsFromGMT()))</pre><pre>let nineAM = now.dateAt(hours: 9, minutes: 30).addingTimeInterval(TimeInterval.init(newYorkTimeZone.secondsFromGMT()))</pre><pre>let fourPM = now.dateAt(hours: 16, minutes: 0).addingTimeInterval(TimeInterval.init(newYorkTimeZone.secondsFromGMT()))  <br>        <br>if !NSCalendar(identifier: .gregorian)!.isDateInWeekend(now) &amp;&amp;<br>       now &gt;= nineAM &amp;&amp;<br>       now &lt;= fourPM{<br>       print(&quot;stockMarketOpen&quot;)<br>       setSession()<br>}else{<br>       print(&quot;stockMarketClose&quot;)<br>            <br>       if let stockSymbol = stockSymbol {<br>              fetchStockPrice(stockSymbol: stockSymbol)<br>       }<br>}</pre><ul><li>function to get 9:00 and 16:00</li></ul><pre>extension Date{</pre><pre>func dateAt(hours: Int, minutes: Int) -&gt; Date{<br>      <br>      let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!<br>      calendar.timeZone = TimeZone(identifier: &quot;America/New_York&quot;)!<br>      <br>      var dateComponents = calendar.components([NSCalendar.Unit.year,<br>                                                NSCalendar.Unit.month,<br>                                                NSCalendar.Unit.day], from: self)<br>      dateComponents.hour = hours<br>      dateComponents.minute = minutes<br>      <br>      let newDate = calendar.date(from:dateComponents)!<br>      return newDate<br>  }<br>}</pre><h3>Github:</h3><p><a href="https://github.com/Luca0508/stockTracker">GitHub - Luca0508/stockTracker</a></p><h3>Link:</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-introduction-app-%E6%A7%8B%E6%83%B3-41c99694a915">美股記帳 App / Introduction. 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%E6%95%99%E5%AE%A4/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part1-watch-list-3205d7fd764f">美股記帳 App / Part1. Watch List</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-2-coredata-nsfetchedresultscontroller-%E5%AD%98%E5%8F%96%E8%B3%87%E6%96%99-ce5418fa95a">美股記帳 App / Part 2. CoreData &amp; NSFetchedResultsController 存取資料</a></li><li><a href="https://medium.com/@juliaxiao860508/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-3-%E5%9D%87%E5%83%B9%E7%8D%B2%E5%88%A9%E8%A8%88%E7%AE%97-charts-%E8%A3%BD%E4%BD%9C%E5%9C%96%E8%A1%A8%E5%88%86%E6%9E%90-b739d3e53ad7">美股記帳 App / Part 3 均價獲利計算 &amp; Charts 製作圖表分析</a></li><li><a href="https://medium.com/@juliaxiao860508/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-5-%E5%B0%8E%E5%85%A5-csv-%E6%AA%94-da404d97cd22">美股記帳 App / Part 5. 導入 .csv 檔</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0d965711ee0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-4-websocket-%E6%8A%93stock-real-time-price-e0d965711ee0">美股記帳 App / Part 4. Websocket 抓stock real time price</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 / Part 3 均價獲利計算 & Charts 製作圖表分析]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-3-%E5%9D%87%E5%83%B9%E7%8D%B2%E5%88%A9%E8%A8%88%E7%AE%97-charts-%E8%A3%BD%E4%BD%9C%E5%9C%96%E8%A1%A8%E5%88%86%E6%9E%90-b739d3e53ad7?source=rss-3448c313725b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b739d3e53ad7</guid>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Julia]]></dc:creator>
            <pubDate>Mon, 21 Mar 2022 16:39:36 GMT</pubDate>
            <atom:updated>2022-04-02T10:59:27.305Z</atom:updated>
            <content:encoded><![CDATA[<h3>功能：</h3><ul><li>Average Price, Average Dollar Cost, Earning, Money Balance</li><li>以個股獲利所製作的 Pie Chart</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FH36E36swj9o%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DH36E36swj9o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FH36E36swj9o%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/44fe0fd791480359558f8788196ec1ab/href">https://medium.com/media/44fe0fd791480359558f8788196ec1ab/href</a></iframe><h3>報表內容</h3><ul><li>totalQuantity ： 股票總共的張數</li><li>totalDollarCost ： 每次交易的金錢總和 （money balance)</li><li>AverageDollarCost ：totalDollarCost / totalQuantity * -1</li><li>AveragePrice ：現有股票的均價</li><li>preAveragePrice ：前一次的均價，方便計算 AveragePriceChange 和 AveragePriceChangePercentage</li><li>Earning: 每一次賣掉股票時，依 AveragePrice 所算的獲利</li></ul><pre>struct stockStatistics : Codable{<br>    let stockSymbol : String<br>    var totalQuantity : Double <br>    var totalDollarCost : Double </pre><pre>    var AverageDollarCost : Double{<br>        if totalQuantity == 0{<br>            return 0<br>        }else{<br>            return totalDollarCost / totalQuantity * -1.0<br>        }<br>    }<br>    <br>    var AveragePrice: Double<br>    var prevAveragePrice : Double<br>    var AveragePriceChange : Double{<br>        return AveragePrice - prevAveragePrice<br>    }<br>    var AveragePriceChangePercentage : Double{<br>        if prevAveragePrice == 0 {<br>            return 0<br>        }<br>        return AveragePriceChange / prevAveragePrice <br>    }<br>    <br>    var earning : Double <br>    var earningChange : Double<br>}</pre><h4>均價算法</h4><ul><li>按時間由早到晚重新將 transactionRecords 排序</li><li>透過 for loop 跑過每一個 transaction</li><li>第一筆交易時，AveragePrice 為購買股票的價格</li><li>買進股票時，AveragePrice 為 ( 買進之前的 AveragePrice 乘以 買進之前的總張數 加上 這次買進的股票價格 乘以 這次買進的張數）除以 買進的總張數</li><li>賣掉股票時，AveragePrice 不變，Earning 為 (賣掉股價 減 AveragePrice ) 乘以 賣掉股票的張數</li><li><strong>經過測試，在股票全部賣掉後，用 AveragePrice 計算的 Earning 會和 Money Balance 一樣，代表這個算法是可行的喔!!!</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18b7bcf7eed5dfd9f8ce5d91fd4f6682/href">https://medium.com/media/18b7bcf7eed5dfd9f8ce5d91fd4f6682/href</a></iframe><h3>Pie Chart</h3><h4>1.下載第三方套件 Charts 並安裝</h4><ul><li><a href="https://github.com/danielgindi/Charts">GitHub - danielgindi/Charts: Beautiful charts for iOS/tvOS/OSX! The Apple side of the crossplatform MPAndroidChart.</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-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></ul><h4>2. 設定 Entry</h4><ul><li>Entry : data value</li><li>使用 map 取出 symbolStock 當 pie chart 的label，並通過 function 得到該股票的 earning 當 pie chart 的 value</li></ul><pre>func getEarning(stockSymbol : String) -&gt; Double{<br>        <br>        if let index = stockStatisticsList.firstIndex(where: {$0.stockSymbol == stockSymbol}){<br>            return stockStatisticsList[index].earning<br>        }<br>        return 0<br>}</pre><pre>let pieChartDataEntries = symbolList.map({(symbol) -&gt; PieChartDataEntry in<br>            return PieChartDataEntry(value: getEarning(stockSymbol: symbol), label:symbol)<br>})<br>        <br>   </pre><h4>3. 設定 dataSet</h4><ul><li>dataSet : 設定 entry 要展現的設定</li><li>selectionShift : 選中的 pie 會往外移多少</li><li>sliceSpace：每個 pie 之間的縫隙</li><li>color : pie 的顏色，因為股票的數量每次可能都不一樣，所以選擇 chartColorTemplates 裡配好的一系列顏色</li></ul><pre>let pieChartDataSet = PieChartDataSet(entries: pieChartDataEntries, label: &quot;&quot;)</pre><pre>pieChartDataSet.selectionShift = 10<br>pieChartDataSet.sliceSpace = 2<br>        <br>pieChartDataSet.colors = ChartColorTemplates.pastel() + ChartColorTemplates.material()</pre><h4>4. 設定 data</h4><ul><li>data : 設定 entry 裡 value 呈現的方式</li><li>setValueFormatter 裡的 input 要遵從 NSObject, protocol: ValueFormatter 所以要額外寫一個 class</li></ul><pre>let pieChartData = PieChartData(dataSet: pieChartDataSet)<br>        <br>pieChartData.setValueFormatter(percentageValueFormatter())<br>pieChartData.setValueFont(.systemFont(ofSize: 12, weight: .regular))<br>pieChartData.setValueTextColor(.white)<br>        <br>class percentageValueFormatter : NSObject,ValueFormatter{<br>      func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -&gt; String {<br>                return String(format: &quot;%.1f%%&quot;, value)<br>      }<br>}</pre><h4>5. 設定 chartView</h4><ul><li>usePerventValuesEnabled : 讓資料以百分比呈現</li><li>animate : 顯示圖的動畫</li><li>sliceTextDrawingThreshold : 如果 pie小於設定的 degree ，pie 裡就不會有文字 （怕 pie 太小，字全都擠在一起）</li></ul><pre>pieChartView.data = pieChartData</pre><pre>pieChartView.usePercentValuesEnabled = <strong>true</strong></pre><pre>pieChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)</pre><pre>pieChartView.sliceTextDrawingThreshold = 20</pre><h4>6. 設定 legend</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*de-eIldCyDX7XS1nhnfxzg.png" /></figure><pre>let legend = pieChartView.legend<br>legend.horizontalAlignment = .center<br>legend.verticalAlignment = .bottom<br>legend.orientation = .horizontal<br>legend.textColor = .white<br>legend.font = UIFont.systemFont(ofSize: 12)<br>legend.form = .circle<br>legend.formToTextSpace = 4<br>legend.formSize = 10</pre><h4>7. 設定 pie chart 中間的字</h4><pre><strong>let</strong> totalEarning = stockStatisticsList.reduce(0.0, {$0 + $1.earning})</pre><pre>pieChartView.centerText = &quot;Total Earning :\n \(totalEarning.getCurrencyFormat())&quot;</pre><h3>Github:</h3><p><a href="https://github.com/Luca0508/stockTracker">GitHub - Luca0508/stockTracker</a></p><h3>Link:</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-introduction-app-%E6%A7%8B%E6%83%B3-41c99694a915">美股記帳 App / Introduction. 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%E6%95%99%E5%AE%A4/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part1-watch-list-3205d7fd764f">美股記帳 App / Part1. Watch List</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-2-coredata-nsfetchedresultscontroller-%E5%AD%98%E5%8F%96%E8%B3%87%E6%96%99-ce5418fa95a">美股記帳 App / Part 2. CoreData &amp; NSFetchedResultsController 存取資料</a></li><li><a href="https://medium.com/@juliaxiao860508/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-4-websocket-%E6%8A%93stock-real-time-price-e0d965711ee0">美股記帳 App / Part 4. Websocket 抓stock real time price</a></li><li><a href="https://medium.com/@juliaxiao860508/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-5-%E5%B0%8E%E5%85%A5-csv-%E6%AA%94-da404d97cd22">美股記帳 App / Part 5. 導入 .csv 檔</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b739d3e53ad7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-3-%E5%9D%87%E5%83%B9%E7%8D%B2%E5%88%A9%E8%A8%88%E7%AE%97-charts-%E8%A3%BD%E4%BD%9C%E5%9C%96%E8%A1%A8%E5%88%86%E6%9E%90-b739d3e53ad7">美股記帳 App / Part 3 均價獲利計算 &amp; Charts 製作圖表分析</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 / Part 2. CoreData & NSFetchedResultsController 存取資料]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-2-coredata-nsfetchedresultscontroller-%E5%AD%98%E5%8F%96%E8%B3%87%E6%96%99-ce5418fa95a?source=rss-3448c313725b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce5418fa95a</guid>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Julia]]></dc:creator>
            <pubDate>Sat, 12 Mar 2022 18:44:18 GMT</pubDate>
            <atom:updated>2022-03-13T03:03:42.496Z</atom:updated>
            <content:encoded><![CDATA[<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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part1-watch-list-3205d7fd764f"><strong>watch list</strong></a> 一樣的方式，將資料存在 Data Container 裡，但考慮到未來要存取的資料一定一天比一天還要龐大，所以改成將資料存在 Core Data</p><h3>記帳功能</h3><ul><li>新增，刪除，修改 交易紀錄</li><li>將資料存在 core data</li><li>用 NSFetchedResultsController update 新增跟修改的資料</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FolqLxmiLwg0%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DolqLxmiLwg0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FolqLxmiLwg0%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/43a6579d19d7068bbaf87f6f1fd0b57f/href">https://medium.com/media/43a6579d19d7068bbaf87f6f1fd0b57f/href</a></iframe><h3>設定 CoreData</h3><p>首先，在建立 project 時先把 Use Core Data的選項勾起來，否則就得像我一樣上網搜尋怎麼之後把 core data 必要的檔案加上</p><h4>SceneDelegate</h4><p>將想要用到 core data 的 controller 放在裡面，透過 tabController &gt;&gt;navigationController &gt;&gt; 想要的 controller 的路徑 指定 controller 讀取 AppDelegate 的資料</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4c72b70bb6e1e99639d18a08155eb84/href">https://medium.com/media/d4c72b70bb6e1e99639d18a08155eb84/href</a></iframe><h4>AppDelegate</h4><ul><li>當資料改變時，立馬儲存資料</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83d83996b7ce1a0b99716562ac9c169b/href">https://medium.com/media/83d83996b7ce1a0b99716562ac9c169b/href</a></iframe><h4>建立 Entities</h4><ul><li>將要存進 CoreData 的資料架構存進去</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iShg2flWso0AhlYRfS674g.png" /></figure><h3>NSFetchedResultsController &amp; NSFetchedResultsControllerDelegate</h3><ul><li>NSFetchedResultsController : 管理從 CoreData fetch 的 data</li><li>NSFetchedResultsControllerDelegate : 當從 CoreData fetch 的 data 有變化時，會出來管理</li></ul><h4>讀取資料</h4><ul><li>NSSortDescriptor : sort data</li><li>NSPredicate : filter data</li><li>記得將獨到的資料存回 local variable</li></ul><pre>if let fetchObject = fetchSpecificResultController.fetchedObjects{<br>       self.transactionRecords = fetchObject<br>}</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8d187129f9c8e81afb22902f71b79ca/href">https://medium.com/media/e8d187129f9c8e81afb22902f71b79ca/href</a></iframe><h4>NSFetchedResultControllerDelegate 更新變動的資料</h4><ul><li>當從 Managed Object Context裡的資料有更動的時候，NSFetchedResultControllerDelegate 會幫我們 update tableView 的內容</li><li>記得在 controller(_:didChange:at:for:newIndexPath:)裡把有變動的資料存回 local variable</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8c98cdf5adf46959b441988897bd3e5/href">https://medium.com/media/f8c98cdf5adf46959b441988897bd3e5/href</a></iframe><h4>從 CoreData 新增，修改，刪除資料</h4><p>因為 addTransaction 有可能把資料傳給兩個不同的 controller，所以我用 delegate 來傳資料</p><ul><li>新增：將資料 insert 回 viewContext，並記得 saveContext</li><li>修改： 只需要 saveContext就好</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22njU1bIKlDXKn2i1Orxyg.png" /></figure><ul><li>刪除： viewContext.delete(removeItem) 並 saveContext</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d60e3a007521a7aca122682e29e43fa/href">https://medium.com/media/7d60e3a007521a7aca122682e29e43fa/href</a></iframe><h4>取出 core data 某一個 variable 的 unique value</h4><p>用在列出使用者都存了哪些股票的 tableViewController，點擊就可以只看特定股票的交易紀錄</p><ul><li>跟之前一樣從 core data 讀取資料</li><li>將讀出來的 array 用 Dictionary 的 group by 功能的到 unique stockSymbol 並把做成 array 給 tableView 用</li><li>在 NSFetchedResultsControllerDelegate 的 extension 裡把有關tableView update 的都刪掉，只剩在 didChange function 裡 存資料重新得到 unique stockSymbol 的 array</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5392c2627c50b2a7140cfb85f4b7217a/href">https://medium.com/media/5392c2627c50b2a7140cfb85f4b7217a/href</a></iframe><h3>GitHub:</h3><p><a href="https://github.com/Luca0508/stockTracker">GitHub - Luca0508/stockTracker</a></p><h3>作品 Link :</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-introduction-app-%E6%A7%8B%E6%83%B3-41c99694a915">美股記帳 App / Introduction. 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%E6%95%99%E5%AE%A4/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part1-watch-list-3205d7fd764f">美股記帳 App / Part1. Watch List</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce5418fa95a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-2-coredata-nsfetchedresultscontroller-%E5%AD%98%E5%8F%96%E8%B3%87%E6%96%99-ce5418fa95a">美股記帳 App / Part 2. CoreData &amp; NSFetchedResultsController 存取資料</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 / Introduction. App 構想]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-introduction-app-%E6%A7%8B%E6%83%B3-41c99694a915?source=rss-3448c313725b------2</link>
            <guid isPermaLink="false">https://medium.com/p/41c99694a915</guid>
            <dc:creator><![CDATA[Julia]]></dc:creator>
            <pubDate>Sat, 12 Mar 2022 07:55:29 GMT</pubDate>
            <atom:updated>2022-03-12T13:13:23.628Z</atom:updated>
            <content:encoded><![CDATA[<p>其實我一開始想要學 iOS App 開發的初衷，是想要用自己記帳的方式，寫出一個幫美股記帳的 App，不僅可以取代原本的 Excel，在手機上操作也比較方便。在上完彼得潘的課後，我終於要來開始實現我的夢想，希望能完成一個我夢寐以求的股票記帳 App</p><h3>About App</h3><p>目前想要分成兩個主要頁面，一個是可以隨時看股票價格，讓使用者加入自己想要的股票的<strong> Watch List ，</strong>另一個就是可以記錄自己股票交易的頁面</p><p>可能還需要加入一個頁面來說明我記帳的方法，讓使用者明白</p><h4>Watch List</h4><ul><li>current price</li><li>price change</li><li>price change (%)</li><li>day high / low</li><li>search bar (可以透過股票代碼或公司名稱搜尋）</li><li>加入，新增，刪除，移動 Watch List 裡的股票</li></ul><h4>記帳功能</h4><ul><li>新增，刪除，修改 交易紀錄</li><li>current price</li><li>想要賺/賠多少錢 就要在什麼價格賣 計算機</li><li>Pie Chart 來記錄擁有股票的 %</li><li>成本，平均價，賺賠多少.......等報表頁面</li></ul><h4>Github:</h4><p><a href="https://github.com/Luca0508/stockTracker">GitHub - Luca0508/stockTracker</a></p><h4>作品 Link:</h4><p><a href="https://medium.com/@juliaxiao860508/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part1-watch-list-3205d7fd764f">美股記帳 App / Part1. Watch List</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41c99694a915" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-introduction-app-%E6%A7%8B%E6%83%B3-41c99694a915">美股記帳 App / Introduction. 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[美股記帳 App / Part1. Watch List]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part1-watch-list-3205d7fd764f?source=rss-3448c313725b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3205d7fd764f</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Julia]]></dc:creator>
            <pubDate>Sat, 12 Mar 2022 07:51:50 GMT</pubDate>
            <atom:updated>2022-04-05T06:48:24.467Z</atom:updated>
            <content:encoded><![CDATA[<p>在構想完後，我決定先從 Watch List 下手，Watch List 可以讓使用者加入想要關注的股票，然後即時跟新股價的相關資訊，下面是我Watch List 會有的功能</p><h4>Watch List</h4><ul><li>current price</li><li>price change</li><li>price change (%)</li><li>day high / low</li><li>search bar (可以透過股票代碼或公司名稱搜尋）</li><li>加入，新增，刪除，移動 Watch List 裡的股票</li><li>將資料存進手機資料夾裡</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*uovfVK2t2AsquRPa5BNWTQ.gif" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYtltpJp6S2c%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYtltpJp6S2c&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYtltpJp6S2c%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/acc96c56c6b02ed11de2f99a8fe2ac74/href">https://medium.com/media/acc96c56c6b02ed11de2f99a8fe2ac74/href</a></iframe><h3>API Source</h3><p>為了得到美股的價格資訊，我採用了 finnhub 的免費 API ，只要輸入 股票的symbol 就可以得到價格資訊</p><p><a href="https://finnhub.io/docs/api/quote">Finnhub - Free realtime APIs for stock, forex and cryptocurrency.</a></p><h3>Search Bar</h3><ul><li>提供使用者方便搜索想要的股票或 ETF</li><li>即使只搜尋公司名字，也能得到正確的股票代碼</li></ul><p>剛開始我打算直接在 search bar 接一個 API ，讓使用者輸入的關鍵字可以接到 Finnhub 的 Symbol Lookup，並得到 下方相關的搜索內容，但試過後發現每多輸入一個字母就連間一次 API 的方式，讓整個 app 變得很卡，搜索出的內容也很廣泛，達不到我心中的預期</p><p>最後決定上網搜尋 美股全部股票還有 ETF 的 List， 用 csv file 的方式讀進 App 裡</p><p><strong>股票與 ETF 的 資料來源</strong></p><ul><li><a href="https://stockmarketmba.com/listoftop100etfs.php">List of Top 100 ETFs</a></li><li><a href="https://www.nasdaq.com/market-activity/stocks/screener">Stock Screener</a></li></ul><h4>讀取 csv 裡的資料</h4><ol><li>下載 CodableCSV</li></ol><pre><a href="https://github.com/dehesa/CodableCSV">https://github.com/dehesa/CodableCSV</a></pre><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-codablecsv-%E8%A7%A3%E6%9E%90-csv-%E4%BB%A5airtable-%E7%82%BA%E4%BE%8B-1cc8bc6a9570">利用 CodableCSV 解析 csv，以Airtable 為例</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-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></ul><p>2. 把 .csv file 放入 Assets 裡，用 .csv file 裡的 column name 建立一個 struct</p><pre>struct stockFullName : Codable{<br>    var Symbol : String<br>    let symbolName :String<br>    var CompanyName : String{<br>        symbolName.components(separatedBy: &quot;_&quot;)[1]<br>    }<br>}</pre><p>3. 建立 extension 把從 csv 裡讀出的檔案變成 array of struct</p><ul><li>csv 裡如果有 header 要設 $0.headerStrategy = .firstLine</li></ul><pre>extension stockFullName {<br>    static var data :[Self]{<br>        var array = [Self]()<br>        if let data = NSDataAsset(name: &quot;stockList&quot;)?.data {<br>            let decoder = CSVDecoder{<br>                $0.headerStrategy = .firstLine<br>            }<br>            do{<br>                array = try decoder.decode([Self].self, from: data)<br>                array = array.filter({!$0.Symbol.contains(&quot;^&quot;)})<br>            }catch{<br>                print(error)<br>            }<br>        }<br>        return array<br>    }<br>}</pre><p>4. 最後叫出data</p><pre>var stockList = stockFullName.data</pre><p>讀取 csv 檔案，可能不是每一個 row 都有 data，這裡我將原本的兩個 column 合併，在 struct 裡在建一個 variable 把 company name 取出來，就可以避免讀取 csv 檔案的 error</p><h4>設定 SearchBar</h4><p>設定 navigationBar 上的 search Controller</p><pre><strong>lazy</strong> <strong>var</strong> filterStockList = stockList<br><strong>var</strong> searching = <strong>false</strong></pre><pre>func searchBarSetting(){<br>        let searchController = UISearchController()<br>        searchController.searchResultsUpdater = self<br>        navigationItem.searchController = searchController<br>        navigationItem.hidesSearchBarWhenScrolling = false<br>        searchController.searchBar.barStyle = .black<br>        searchController.searchBar.searchTextField.textColor = .white<br>        searchController.automaticallyShowsCancelButton = true<br>    }</pre><p>加一個 extension 來 update 搜尋的結果</p><pre>extension SearchStockTableViewController : UISearchResultsUpdating{<br>    func updateSearchResults(for searchController: UISearchController) {<br>        if let searchText = searchController.searchBar.text,<br>           searchText.isEmpty == false{<br>            searching = true<br>            filterStockList = stockList.filter({ stock in<br>                stock.symbolName.localizedStandardContains(searchText)<br>            })<br>            <br>        }else{<br>            searching = false<br>            filterStockList = stockList<br>        }<br>        <br>        tableView.reloadData()<br>    }<br>}</pre><h4>用 delegate 傳資料回 watchList</h4><p>因為搜尋股票這個功能之後在記帳的時候也會用到，所以選擇用delegate 傳資料，方便在不同的時候傳 stock symbol 去不同的頁面</p><h4>透過 API 抓取股價</h4><p><a href="https://finnhub.io/docs/api/quote">Finnhub - Free realtime APIs for stock, forex and cryptocurrency.</a></p><ol><li>按造 API 的資料架構建一個 struct</li><li>連接 API</li></ol><ul><li>URLQueryItem 裡的 symbol 用的是從 searchStockTableViewController 傳過來的 stock symbol</li></ul><pre>func fetchItem(stockInfo:stockFullName){<br>        let token = &quot;c7occ8iad3idf06mr490&quot;<br>        <br>        var stockUrlComponent = URLComponents(string: &quot;<a href="https://finnhub.io/api/v1/quote">https://finnhub.io/api/v1/quote</a>&quot;)<br>        stockUrlComponent?.queryItems = [<br>            URLQueryItem(name: &quot;symbol&quot;, value: stockInfo.Symbol),<br>            URLQueryItem(name: &quot;token&quot;, value: token)<br>        ]<br>        <br>        URLSession.shared.dataTask(with: (stockUrlComponent?.url)!) { data, response, error in<br>            if let data = data {<br>                let decoder = JSONDecoder()<br>                do{<br>                    var apiResponse = try decoder.decode(stockPriceInfo.self, from: data)<br>                    apiResponse.symbol = stockInfo.Symbol<br>                    apiResponse.company = stockInfo.CompanyName<br>                    self.watchList.append(apiResponse)<br>                    <br>                    DispatchQueue.main.sync {<br>                        self.tableView.reloadData()<br>                    }<br>                    <br>                }catch{<br>                    print(error)<br>                }<br>                <br>            }<br>        }.resume()<br>        <br>    }</pre><h4>把 watchList 的資料存入手機的資料夾</h4><ul><li>data container 的資料使可以修改的，所以用 FileManger.default.urls建立存資料的地方</li><li>用 JSONDecoder 和 JSONEncoder 取出或存入資料</li></ul><pre>struct stockPriceInfo: Codable{<br>    var symbol : String?<br>    var company : String?<br>    var c: Double // current price<br>    var d: Double // change<br>    var dp: Double // percent change<br>    var h : Double // high price of the day<br>    var l : Double// low price of the day<br>//    let o : Double // open pirce of the day<br>//    let pc : Double // previous close price</pre><pre>    static var documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!<br>    <br>    static func loadWatchList() -&gt; [stockPriceInfo]?{<br>        let url = documentDirectory.appendingPathComponent(&quot;watchList&quot;)<br>        guard let data = try? Data(contentsOf: url) else {return nil}<br>        <br>        let decoder = JSONDecoder()<br>        return try? decoder.decode([stockPriceInfo].self, from: data)<br>    }<br>    <br>    static func saveWatchList(_ watchList: [Self]){<br>        let encoder = JSONEncoder()<br>        guard let data = try? encoder.encode(watchList) else {return }<br>        let url = documentDirectory.appendingPathComponent(&quot;watchList&quot;)<br>        try? data.write(to: url)<br>        <br>    }<br>}</pre><p>在 watchListTableViewController,</p><ul><li>viewDidLoad 時會讀取存在手機的資料</li><li>當 watchList有任何更改時，didSet 裡會將資料存回去手機資料庫裡</li></ul><pre>var watchList = [stockPriceInfo](){<br>        didSet{<br>            stockPriceInfo.saveWatchList(watchList)<br>        }<br>    }<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        if let watchList = stockPriceInfo.loadWatchList(){<br>            self.watchList = watchList<br>        }</pre><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        if let watchList = stockPriceInfo.loadWatchList(){<br>            self.watchList = watchList<br>        }<br>}</pre><h4>定時更新資料</h4><ul><li>每五秒更新一次股價</li><li>記得要 timer.fire(), timer才會啟動</li></ul><pre>let timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in<br>            for stock in self.watchList{<br>                self.fetchExistingItem(stockInfo: stock)<br>            }<br>            self.tableView.reloadData()<br>        }<br>        timer.fire()</pre><h3>Github:</h3><p><a href="https://github.com/Luca0508/stockTracker">GitHub - Luca0508/stockTracker</a></p><h3>作品 Link:</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-introduction-app-%E6%A7%8B%E6%83%B3-41c99694a915">美股記帳 App / Introduction. App 構想</a></li><li><a href="https://medium.com/@juliaxiao860508/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-2-coredata-nsfetchedresultscontroller-%E5%AD%98%E5%8F%96%E8%B3%87%E6%96%99-ce5418fa95a">美股記帳 App / Part 2. CoreData &amp; NSFetchedResultsController 存取資料</a></li><li><a href="https://medium.com/@juliaxiao860508/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-3-%E5%9D%87%E5%83%B9%E7%8D%B2%E5%88%A9%E8%A8%88%E7%AE%97-charts-%E8%A3%BD%E4%BD%9C%E5%9C%96%E8%A1%A8%E5%88%86%E6%9E%90-b739d3e53ad7">美股記帳 App / Part 3 均價獲利計算 &amp; Charts 製作圖表分析</a></li><li><a href="https://medium.com/@juliaxiao860508/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-4-websocket-%E6%8A%93stock-real-time-price-e0d965711ee0">美股記帳 App / Part 4. Websocket 抓stock real time price</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/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part-5-%E5%B0%8E%E5%85%A5-csv-%E6%AA%94-da404d97cd22">美股記帳 App / Part 5. 導入 .csv 檔</a></li><li><a href="https://medium.com/@juliaxiao860508/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part6-%E5%BE%9E-cocoapods-%E5%AE%89%E8%A3%9D%E5%A5%97%E4%BB%B6%E4%BE%86%E8%A3%BD%E4%BD%9C-sidemenu-%E5%92%8C-%E5%AF%AB%E6%95%B8%E5%AD%B8%E5%85%AC%E5%BC%8F-136ef00f2a23">美股記帳 App / Part6. 從 cocoapods 安裝套件來製作 sidemenu 和 寫數學公式</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3205d7fd764f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E7%BE%8E%E8%82%A1%E8%A8%98%E5%B8%B3-app-part1-watch-list-3205d7fd764f">美股記帳 App / Part1. Watch List</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 WorldClock]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E6%A8%A1%E4%BB%BF-ios-worldclock-a9bac2485505?source=rss-3448c313725b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9bac2485505</guid>
            <category><![CDATA[world-clock]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Julia]]></dc:creator>
            <pubDate>Sun, 20 Feb 2022 05:34:32 GMT</pubDate>
            <atom:updated>2022-02-21T05:52:14.798Z</atom:updated>
            <content:encoded><![CDATA[<p>資料儲存練習，用 delegate 傳資料</p><p>這次作業模仿 iPhone內建的 worldClock 來練習 table view controller 的新增，刪除，和儲存資料</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*wr3hjE3ycF2t6KEubDEF2Q.gif" /></figure><h4>1. 取得世界城市 timezone 的清單</h4><pre>let knownTimeZoneID = TimeZone.knownTimeZoneIdentifiers.filter { ID in<br>    ID.contains(&quot;/&quot;)<br>}</pre><h4>2. 建立列表上所要顯示的資料</h4><ul><li>identify : 從 TimeZone.knownTimeZoneIdentifiers 裡得到的 ID</li><li>cityName : 取 id / 後面的城市名</li><li>cityPrefix : 取城市的第一個字母，在 searchTableViewController 裡當 section 的名字用</li><li>relativeDate : 相對local 的日期，顯示 昨天、今天、明天</li><li>relativeHour：相對 local 的小時差 Ex: +- HRs</li><li>localTime ： 當地時間</li></ul><pre>struct cityInfo: Codable{<br>    <br>    <br>    var identify: String<br>    var cityName: String {<br>        let fullName = identify.replacingOccurrences(of: &quot;_&quot;, with: &quot; &quot;).components(separatedBy: &quot;/&quot;)<br>        if fullName.count &gt; 2{<br>            return fullName[1] + &quot;, &quot; + fullName[2]<br>        }<br>        <br>        return fullName[1]<br>    }<br>    var cityPrefix : String{<br>        return String(cityName.prefix(1))<br>    }<br>    <br>    var relativeDate : String{<br>        let dateformatter = DateFormatter()<br>        dateformatter.timeZone = TimeZone(identifier: identify)<br>        dateformatter.dateStyle = .medium<br>        dateformatter.timeStyle = .none<br>        dateformatter.doesRelativeDateFormatting = true<br>        <br>        return dateformatter.string(from: .now) + &quot;,&quot;<br>        <br>    }<br>    <br>    var relativeHour : String {<br>        <br>        let hrInterval = (TimeZone(identifier: identify)!.secondsFromGMT() - TimeZone.current.secondsFromGMT())/3600<br>        if hrInterval == 1 || hrInterval == -1 {<br>            return hrInterval.description + &quot;HR&quot;<br>        }<br>        return hrInterval.description + &quot;HRS&quot;<br>    }<br>    <br>    var localTime : String{<br>        let dateformatter = DateFormatter()<br>        dateformatter.timeZone = TimeZone(identifier: identify)<br>        dateformatter.dateFormat = &quot;HH:mm&quot;<br>        return dateformatter.string(from: .now)<br>    }<br>}</pre><h4>3. 建立搜索的頁面</h4><ul><li><strong>幫城市建立一個 dictionary， key 是 cityPrefix (也是 section header）， value 是 以那個字母為開頭的 array of cityInfo</strong></li></ul><pre><strong>var</strong> delegate : SearchTableViewControllerDelegate?<br>var cityDictionary = [String : [cityInfo]]()<br>var cityDictinaryKey = [String]()<br>var searching = false<br>lazy var filterCityList = knownCityList<br>var knownCityList = [cityInfo]()<br>var city : cityInfo?</pre><pre><br>func sectionHeaderSetting(){<br>        for cityID in knownTimeZoneID{<br>            let city = cityInfo(identify: cityID)<br>            knownCityList.append(city)<br>            <br>            if cityDictionary.keys.contains(city.cityPrefix){<br>                cityDictionary[city.cityPrefix]!.append(city)<br>            }else{<br>                cityDictionary[city.cityPrefix] = [city]<br>            }<br>        }<br>        cityDictinaryKey = Array(cityDictionary.keys).sorted(by: &lt;)<br>    }</pre><ul><li><strong>設定 number of sections and number of rows in section 和要顯示的內容</strong></li></ul><p>在搜尋的時候沒有按字母分 section，所以設一個 var boolean variable 來看當時有沒有在搜尋，並用 if statement 把他分成兩個狀況顯示</p><pre>override func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        if searching {<br>            return 1<br>        }<br>        return cityDictionary.count<br>    }<br>    <br>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        if searching {<br>            return filterCityList.count<br>        }<br>        return cityDictionary[cityDictinaryKey[section]]!.count<br>    }</pre><pre>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        guard let cell = tableView.dequeueReusableCell(withIdentifier: &quot;\(SearchTableViewCell.self)&quot;, for: indexPath) as? SearchTableViewCell else {return UITableViewCell()}<br>        <br>        if searching {<br>            let cityId = filterCityList[indexPath.row]<br>            cell.SearchCityLabel.text = cityId.cityName<br>        }else{<br>            let cityId = cityDictionary[cityDictinaryKey[indexPath.section]]![indexPath.row]<br>            <br>            cell.SearchCityLabel.text = cityId.cityName</pre><pre>        }<br>        <br>        return cell<br>}<br>    <br>override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -&gt; String? {<br>        <br>        if searching {<br>            return nil<br>        }<br>       <br>        return cityDictinaryKey[section]<br>}</pre><ul><li><strong>參考下面那篇文章，在navigationBar 上設立 searchBar</strong></li></ul><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/navigation-bar-%E8%A3%A1%E9%A1%AF%E7%A4%BA-search-bar-a63aa932d0b9">利用 UISearchController 實現 search 功能</a></p><pre>func searchBarSetting(){<br>        let searchController = UISearchController()<br>        searchController.searchResultsUpdater = self<br>        navigationItem.searchController = searchController<br>        navigationItem.hidesSearchBarWhenScrolling = false<br>        searchController.searchBar.barStyle = .black<br>        searchController.searchBar.searchTextField.textColor = .white<br>        searchController.automaticallyShowsCancelButton = true<br>    }</pre><ul><li><strong>實現 search 的時候 下面的資料也會跟著 搜索關鍵字 update</strong></li></ul><p>會用到之前的 lazy var filterCityList = knownCityList</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/%E8%AE%93%E5%B1%AC%E6%80%A7%E8%AE%8A%E6%87%B6%E7%9A%84-swift-lazy-%E5%92%92%E8%AA%9E-cfcc16840bd2">讓屬性變懶的 swift lazy 咒語</a></p><p>記得最後要讓 tableView reload data ，畫面才會 update</p><pre>extension SearchTableViewController : UISearchResultsUpdating{<br>    func updateSearchResults(for searchController: UISearchController) {<br>        <br>        if let searchText = searchController.searchBar.text,<br>           searchText.isEmpty == false{<br>            searching = true<br>            filterCityList = knownCityList.filter({ city in<br>                city.cityName.localizedStandardContains(searchText)<br>            })<br>            <br>            <br>        }else{<br>            searching = false<br>            filterCityList = knownCityList<br>        }<br>        <br>        tableView.reloadData()<br>        <br>    }<br>}</pre><ul><li><strong>把選到的資料傳回上一頁 （unwind segue)</strong></li></ul><pre>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>        if searching{<br>            guard let row = tableView.indexPathForSelectedRow?.row else {return }<br>            city = filterCityList[row]<br>        }else {<br>            guard let section = tableView.indexPathForSelectedRow?.section else {return }<br>            guard let row = tableView.indexPathForSelectedRow?.row else {return }<br>            city = cityDictionary[cityDictinaryKey[section]]![row]<br>        }<br>    }</pre><h4><strong>3. 建立世界時鐘的清單頁面</strong></h4><ul><li><strong>儲存使用者選擇的城市資料</strong></li></ul><p>struct 要是 codable才能讀取跟存資料 ，並把資料存在 document 資料夾裡</p><pre>struct cityInfo: Codable{<br>    // save and load data<br>    static let documentDictionary = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!<br>    <br>    static func loadData() -&gt; [cityInfo]?{<br>        let url = documentDictionary.appendingPathComponent(&quot;cityList&quot;)<br>        guard let data = try? Data(contentsOf: url) else {return nil}<br>        let decoder = JSONDecoder()<br>        return try? decoder.decode([cityInfo].self, from: data)<br>        <br>    }<br>    <br>    static func saveInfo(info :[cityInfo]){<br>        let encoder = JSONEncoder()<br>        guard let data = try? encoder.encode(info) else {return }<br>        let url = documentDictionary.appendingPathComponent(&quot;cityList&quot;)<br>        try? data.write(to: url)<br>    }<br>}</pre><p>在 worldClockTableViewController 裡在叫出function 讀取還有存資料</p><p>didSet 會在新的值存進去的時候被叫出來</p><p>記得讓 timer 每一秒重新 reload data ，時間才會跟著動</p><pre>var cityList = [cityInfo](){<br>        didSet{<br>            cityInfo.saveInfo(info: cityList)<br>        }<br>    }</pre><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        if let cityList = cityInfo.loadData(){<br>            self.cityList = cityList<br>        }<br>        <br>        tableView.rowHeight = 90<br>        tableView.separatorStyle = .singleLine<br>        tableView.separatorColor = .gray<br>        <br>        let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { _ in<br>            self.tableView.isEditing ? nil : self.tableView.reloadData()<br>        }<br>        timer.fire()<br>        <br>        <br>    }</pre><ul><li><strong>讓使用者可以刪除或移動想要的順序 並設定 Edit button</strong></li></ul><p>super.setEditing( ) 可以讓我們edit table view</p><p>isEditing 可以告訴我們當下有沒有正在 edit (boolean value)</p><pre>override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {<br>        cityList.remove(at: indexPath.row)<br>        tableView.deleteRows(at: [indexPath], with: .automatic)<br>    }</pre><pre>// Override to support conditional editing of the table view.<br>override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -&gt; Bool {<br>        // Return false if you do not want the specified item to be editable.<br>        return true<br>    }</pre><pre>// make the cell become movable<br>    // Override to support conditional rearranging of the table view.<br>override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -&gt; Bool {<br>        // Return false if you do not want the item to be re-orderable.<br>        return true<br>    }<br>    <br>    // Override to support rearranging the table view.<br>override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {<br>        let removeItem = cityList[fromIndexPath.row]<br>        cityList.remove(at: fromIndexPath.row)<br>        cityList.insert(removeItem, at: to.row)</pre><pre>}</pre><pre><a href="http://twitter.com/IBAction">@IBAction</a> func clickEditButton(_ sender: UIBarButtonItem) {<br>        // set whether the view controller show the editable view<br>        super.setEditing(!tableView.isEditing , animated: true)<br>        sender.title = isEditing ? &quot;Done&quot;: &quot;Edit&quot;<br>        <br>        tableView.allowsSelectionDuringEditing = true<br>        tableView.reloadData()<br>        <br>    }</pre><h4>4. 用 delegate 把資料傳回前一頁</h4><p>本來這裡我是用 unwind segue傳資料的，但發現用 search bar 搜尋城市後，要點兩次才能傳回前一頁，卡了很久後，再經過 Peter 的神救援，改用 tableView(_:didSelectRowAt:) 和 delegate傳資料</p><ul><li><strong>建立 protocol並呼叫裡面的 function</strong></li></ul><p>In SearchViewTableViewController,</p><pre>protocol SearchTableViewControllerDelegate {<br>    func searchTableViewController( _ controller : SearchTableViewController, addCity city:cityInfo)<br>}</pre><pre>class SearchTableViewController: UITableViewController {<br>    <br>    var delegate : SearchTableViewControllerDelegate?<br>    <strong>var</strong> city : cityInfo?</pre><pre><br>override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>        if searching{<br>            city = filterCityList[indexPath.row]<br>        }else {</pre><pre>city = cityDictionary[cityDictinaryKey[indexPath.section]]![indexPath.row]<br>        }<br>        delegate?.searchTableViewController(self, addCity: city!)<br>        <br>        navigationController?.popViewController(animated: true)<br>    }</pre><pre>}</pre><ul><li><strong>連一個 IBSegueAction, 在裡面設定 delegate，記得也要繼承 SearchTableViewControllerDelegate</strong></li></ul><p>In WorldClockTableViewController,</p><pre><a href="http://twitter.com/IBSegueAction">@IBSegueAction</a> func addCity(_ coder: NSCoder) -&gt; SearchTableViewController? {<br>        let searchTableViewController =  SearchTableViewController(coder: coder)<br>        searchTableViewController?.delegate = self<br>        return searchTableViewController<br>    }</pre><p>繼承 SearchTableViewControllerDelegate ，寫一個一樣的function 名，並在 function 裡面放想做的事</p><pre>extension WorldClockTableViewController : SearchTableViewControllerDelegate{<br>    <br>    func searchTableViewController( _ controller : SearchTableViewController, addCity city:cityInfo){<br>        <br>        if !(cityList.contains(where: { cityInfo in<br>            cityInfo.cityName == city.cityName<br>        })){<br>            cityList.append(city)<br>        }<br>        tableView.reloadData()<br>    }<br>}</pre><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-delegate-%E8%AE%93%E4%B8%8D%E5%90%8C%E5%85%83%E4%BB%B6%E6%BA%9D%E9%80%9A-%E4%BB%A5%E8%B3%87%E6%96%99%E5%9B%9E%E5%82%B3%E5%88%B0%E5%89%8D%E4%B8%80%E9%A0%81-controller-%E7%82%BA%E4%BE%8B-ba215f3d2596">利用 delegate 讓不同元件溝通，以資料回傳到前一頁 controller 為例</a></li><li><a href="https://developer.apple.com/documentation/uikit/uitableviewdelegate/1614877-tableview">tableView(_:didSelectRowAt:) | Apple Developer Documentation</a></li></ul><p><strong>最後，特別感謝 Peter 的神救援，還有下面這位前輩的作業參考，才能成功將這個作業做出來！！！</strong></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%E6%95%99%E5%AE%A4/27-%E6%A8%A1%E4%BB%BF-ios-clock-app-1-world-clock-e2b6f70cc2ca">#27 模仿 iOS Clock App - 1 ：World Clock</a></p><p>Link:</p><ul><li><a href="https://stackoverflow.com/questions/47494222/getting-the-city-country-list-in-ios-time-zone">Getting the City &amp; Country list in iOS Time Zone</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/27-%E6%A8%A1%E4%BB%BF-ios-clock-app-1-world-clock-e2b6f70cc2ca">#27 模仿 iOS Clock App - 1 ：World Clock</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/navigation-bar-%E8%A3%A1%E9%A1%AF%E7%A4%BA-search-bar-a63aa932d0b9">利用 UISearchController 實現 search 功能</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-delegate-%E8%AE%93%E4%B8%8D%E5%90%8C%E5%85%83%E4%BB%B6%E6%BA%9D%E9%80%9A-%E4%BB%A5%E8%B3%87%E6%96%99%E5%9B%9E%E5%82%B3%E5%88%B0%E5%89%8D%E4%B8%80%E9%A0%81-controller-%E7%82%BA%E4%BE%8B-ba215f3d2596">利用 delegate 讓不同元件溝通，以資料回傳到前一頁 controller 為例</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/65-%E6%A8%A1%E4%BB%BF%E8%A3%BD%E4%BD%9C-ios-%E5%85%A7%E5%BB%BA%E7%9A%84-clock-app-29385a04bea">#65 模仿製作 iOS 內建的 Clock App</a></li></ul><p>GitHub:</p><p><a href="https://github.com/Luca0508/worldClock">GitHub - Luca0508/worldClock</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9bac2485505" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E6%A8%A1%E4%BB%BF-ios-worldclock-a9bac2485505">模仿 iOS WorldClock</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[實作 Table View 功能 - Mamamoo成員 solo 歌曲列表]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E5%AF%A6%E4%BD%9C-table-view-%E5%8A%9F%E8%83%BD-mamamoo%E6%88%90%E5%93%A1-solo-%E6%AD%8C%E6%9B%B2%E5%88%97%E8%A1%A8-236c36981ab1?source=rss-3448c313725b------2</link>
            <guid isPermaLink="false">https://medium.com/p/236c36981ab1</guid>
            <category><![CDATA[table-view-controller]]></category>
            <category><![CDATA[mamamoo]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Julia]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 04:43:45 GMT</pubDate>
            <atom:updated>2022-01-21T06:18:47.494Z</atom:updated>
            <content:encoded><![CDATA[<p>HW #51 實作TableView的基本公能</p><p>這次嘗試模仿了 Spotify 的排版還有他的愛心功能，連圖片都是從 Spotify 上截圖的喔</p><p>下面是短短的 gif demo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*6s_iqtWAzWnIqNCrMTx5LQ.gif" /></figure><p>私心附上有 mv 片段的 App錄屏</p><p>這個月，我的本命帶著快時隔兩年的solo 專輯回歸囉 ！ 主打歌又是我超愛的psycho 主題，快點擊下面一起欣賞超好聽的音樂 （到底是哪一個psycho 可以上一秒可愛下一秒又那麼帥氣啦 ！！！！！）</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMOWUfEOGBG8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMOWUfEOGBG8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMOWUfEOGBG8%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/02807aec26c4f29e87a10e1464334fa7/href">https://medium.com/media/02807aec26c4f29e87a10e1464334fa7/href</a></iframe><h4>建立客製化的 TableViewCell</h4><ul><li>把 TableViewCell 換成custom 並幫他取一個 identifier</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*ZpOlkHMB95FtZ4bHO_GtWA.png" /></figure><ul><li>在裡面放好想要的物件後，建一個 subclass 是 UITableViewCell 的file 幫物件拉 IBOutlet</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yh0mdXr2LSnagQL21kW-Jw.png" /></figure><h4>幫放進cell裡的資料建立 struct</h4><ul><li>like variable 決定有沒有按愛心按鈕，會隨著使用者操作變換，所以 like, 裝有 songInfo 的 songList, 和裝有singerInfo 的 playList都要用 var</li></ul><pre>struct songInfo{<br>    let singerName :String<br>    let songTitle: String<br>    let imageName : String<br>    let url : String<br>    var like : Bool<br>}</pre><pre>struct singerInfo {<br>    let singerName :String<br>    var songList : Array&lt;songInfo&gt;<br>}</pre><ul><li>再以套娃的方式把每一個歌手的資料放進Array裡，就能擁有 section 和 row 資料</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDLtrxVlIRi7ENR3nQl9LA.png" /></figure><h4>設定要有幾個section 和 row</h4><pre>override func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        // #warning Incomplete implementation, return the number of sections<br>        return playList.count<br>    }</pre><pre>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        // #warning Incomplete implementation, return the number of rows<br>        return playList[section].songList.count<br>    }</pre><h4>連結到tableViewController</h4><p>把之前幫 tableViewCell 取的 identifier 放進 dequeueReusableCell(withIdentifier: propertyKey.songCell, for: indexPath) 然後用 as?轉成 剛剛幫tableViewCell 建立的class</p><pre>struct propertyKey {<br>        static let songCell = &quot;songCell&quot;<br>    }</pre><pre>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        guard let cell = tableView.dequeueReusableCell(withIdentifier: propertyKey.songCell, for: indexPath) as? playListTableViewCell else {return UITableViewCell()}</pre><pre>let song = playList[indexPath.section].songList[indexPath.row]<br>        cell.singerLabel.text = song.singerName<br>        cell.songTitleLabel.text = song.songTitle<br>        cell.songImageView.image = UIImage(named: song.imageName)</pre><pre>        if song.like == true {<br>            cell.heartButton.setImage(UIImage(systemName: &quot;heart.fill&quot;), for: .normal)<br>            cell.heartButton.tintColor = .green<br>        }else {<br>            cell.heartButton.setImage(UIImage(systemName: &quot;heart&quot;), for: .normal)<br>            cell.heartButton.tintColor = .lightGray<br>        }<br>        <br>        return cell<br>    }</pre><h4>模仿 Spotify 設定愛心按鈕</h4><ul><li>因為 tableViewCell 會重複利用 （dequeueReusableCell），所以按完按鈕後，要將改變後的值存回 songInfo，不然會複製到後面的 cell</li><li>用下面的方把找到按鈕在 tableView 上的座標，並對應得到第幾個row，在把值案照row number 給存回 songInfo</li></ul><pre>let point = sender.convert(CGPoint.zero, to: tableView)<br>if let indexPath = tableView.indexPathForRow(at: point){<br>    ...<br>}</pre><pre><a href="http://twitter.com/IBAction">@IBAction</a> func heartButtonChange(_ sender: UIButton) {<br>        let point = sender.convert(CGPoint.zero, to: tableView)<br>        if let indexPath = tableView.indexPathForRow(at: point){<br>            if sender.imageView?.image == UIImage(systemName: &quot;heart&quot;){<br>                playList[indexPath.section].songList[indexPath.row].like = true<br>                sender.setImage(UIImage(systemName: &quot;heart.fill&quot;), for: .normal)<br>                sender.tintColor = .green<br>            } else if sender.imageView?.image == UIImage(systemName: &quot;heart.fill&quot;){<br>                playList[indexPath.section].songList[indexPath.row].like = false<br>                <br>                sender.setImage(UIImage(systemName: &quot;heart&quot;), for: .normal)<br>                sender.tintColor = .lightGray<br>            }<br>            <br>        }<br>        <br>}</pre><h4>幫每個section 設定header</h4><ul><li>設定 section 裡的內容</li></ul><pre>override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -&gt; String? {<br>        return playList[section].singerName<br>    }</pre><ul><li>設定背景顏色還有字型</li></ul><pre>override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {<br>        let headerView = view as! UITableViewHeaderFooterView<br>        headerView.contentView.backgroundColor = .black<br>        headerView.textLabel?.textColor = .white<br>        headerView.textLabel?.font = .systemFont(ofSize: 26, weight: .bold)<br>        headerView.textLabel?.sizeToFit()<br>    }</pre><ul><li>設定header 的高度</li></ul><pre>override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -&gt; CGFloat {<br>        return 50<br>    }</pre><pre>}</pre><h4>用IBSegueAction 將要傳的資料傳過去</h4><ul><li>Segue 要從 table cell 連到下一個View （不是從 View 連到下一個 View ）</li></ul><pre><a href="http://twitter.com/IBSegueAction">@IBSegueAction</a> func showWebSite(_ coder: NSCoder) -&gt; playListWebViewController? {<br>        guard let section = tableView.indexPathForSelectedRow?.section else {return nil}<br>        guard let row = tableView.indexPathForSelectedRow?.row else {return nil}<br>        let song = playList[section].songList[row]<br>        return playListWebViewController(coder: coder, song: song)<br>    }</pre><h4>顯示對應的 YouTube MV 網頁</h4><ul><li>將WebView 連IBOutlet</li><li>記得要 <strong>import</strong> WebKit</li></ul><pre><strong>@IBOutlet</strong> <strong>weak</strong> <strong>var</strong> youtubeWebView: WKWebView!<br>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        let request = URLRequest(url: URL(string: song.url)!)<br>        youtubeWebView.load(request)<br>}</pre><h4>Github:</h4><p><a href="https://github.com/Luca0508/TableViewMusicPlayer">GitHub - Luca0508/TableViewMusicPlayer</a></p><h4>Link:</h4><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/51-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-8f52cc9d2bf1">#51 實作 Table View 的基本功能</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/%E9%81%8B%E7%94%A8tableview%E5%AF%A6%E4%BD%9Cyoutube%E8%A7%80%E7%9C%8B%E7%B4%80%E9%8C%84%E9%A0%85%E7%9B%AE-2245e3bcb9e9">運用TableView實作YouTube觀看紀錄項目</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=236c36981ab1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E5%AF%A6%E4%BD%9C-table-view-%E5%8A%9F%E8%83%BD-mamamoo%E6%88%90%E5%93%A1-solo-%E6%AD%8C%E6%9B%B2%E5%88%97%E8%A1%A8-236c36981ab1">實作 Table View 功能 - Mamamoo成員 solo 歌曲列表</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/%E7%85%A7%E7%89%87%E7%B7%A8%E8%BC%AF-app-657de763763b?source=rss-3448c313725b------2</link>
            <guid isPermaLink="false">https://medium.com/p/657de763763b</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mamamoo]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Julia]]></dc:creator>
            <pubDate>Thu, 13 Jan 2022 04:06:30 GMT</pubDate>
            <atom:updated>2022-01-13T08:40:27.421Z</atom:updated>
            <content:encoded><![CDATA[<p>UIAlertController, UIImagePickerController, CGAffineTransform, UIGraphicsImageRenderer. UIScrollView</p><h4>App 功能 ：</h4><ul><li>選取照片</li><li>鏡像翻轉</li><li>90度旋轉</li><li>改變照片的大小</li><li>儲存修改後的圖</li></ul><p>下面是App 的gif，有人有發現第一張躲在角落監視女明星奴才的貓就是第二張的厭世貓嗎？他也是世界上我最想魂穿的貓喔！！畢竟誰不想當一隻懶洋洋的高冷貓，還能天天沐浴在自家偶像的歌聲裡</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*3J3iZZejnS3l6sHRNDL3xA.gif" /></figure><p>為了讓大家更方便欣賞貓咪的高顏值，下面是 App 的螢幕錄製影片</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyiHLYSOjHJU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyiHLYSOjHJU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyiHLYSOjHJU%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/7242e14d10de09001527d940356e11db/href">https://medium.com/media/7242e14d10de09001527d940356e11db/href</a></iframe><h3>選取圖片</h3><ul><li>在 selectPhoto 的 function 裡，幫 UIImagePickerController 設定delegate 還有要哪裡選取圖片的地方 (sourceType)</li><li>用 UIAlertController 問使用者要選自圖庫還是相機 (preferredStyle: UIAlertController.Style.actionSheet)</li><li>用 for loop 來 addAction</li></ul><pre>let action = UIAlertAction(title: s.title, style: .default){_ in<br>                self.selectPhoto(sourceType: s.sourceType)<br>            }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urb3d04HrHitCsJ9wL1Lrg.png" /></figure><ul><li>選完照片後會直接跳到 edit Photo 的頁面</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PAQshZUGqTY2L35M8V5wXQ.png" /></figure><h4>讓圖片在ScrollView 裡有正常的大小</h4><ul><li>讓view的長寬除以 image (不是imageView!!!）的長寬，將所得到的 scale 設置為 ScrollView 的 scale</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*EtyJax6RLZcrb0hfeEb0hA.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/%E5%88%A9%E7%94%A8-scroll-view-%E7%B8%AE%E6%94%BE%E5%9C%96%E7%89%87-72960fb1b332">利用 scroll view &amp; contentInset 縮放置中圖片</a></p><h3>修改圖片</h3><p>為了讓用不同功能的時候，還能讓圖片記得上一個功能修改完的結果，所以用套娃的方式把很多個View 包起來</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*zeC2gWJauqp7ihtGhSa3ew.png" /></figure><h4>圖片翻轉90 度</h4><ul><li>每翻轉一次加就加一，然後讓翻轉次數乘以90度</li></ul><pre>rotateTimes += 1<br>            rotateView.transform = CGAffineTransform(rotationAngle: CGFloat.pi/180*90 * CGFloat(rotateTimes))</pre><h4>鏡像翻轉</h4><ul><li>每變一次就乘以 -1</li></ul><pre>mirrorVariable *= -1<br>            mirrorView.transform = CGAffineTransform(scaleX: CGFloat(mirrorVariable), y: 1)</pre><h4>改變照片比例</h4><ul><li>先取的原本View的長和寬 ，依照比例調整得到新的長跟寬之後，再帶到ScrollView 的frame.size</li><li>讓ScrollView在View 的中間</li></ul><pre>photoScrollView.center = CGPoint(x: origWidth/2, y: origHeight/2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*EgAGZBz0zGj_zJ0W0NL5Jg.png" /></figure><h3>儲存圖片</h3><ul><li>用 UIGraphicsImageRenderer 將 view 轉成圖片</li><li>用 UIActivityViewController 分享圖片</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQifrQdi6KBg63xB-KDcFg.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/%E5%88%A9%E7%94%A8-uigraphicsimagerenderer-%E5%B0%87-view-%E8%AE%8A%E6%88%90%E5%9C%96%E7%89%87-41d00c568903">利用 UIGraphicsImageRenderer 將 view 變成圖片(包含只擷取 view 的部分區塊）</a></p><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%E6%95%99%E5%AE%A4/protocol-delegate%E7%B7%B4%E7%BF%92-%E7%85%A7%E7%89%87%E7%B7%A8%E8%BC%AFapp-39ee55376bf1">Protocol&amp;Delegate練習｜照片編輯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%E6%95%99%E5%AE%A4/%E4%BD%9C%E6%A5%AD-49-%E7%85%A7%E7%89%87%E7%B7%A8%E8%BC%AFapp-66325d07189e">作業#49 照片編輯App</a></li></ul><h4><strong>Github:</strong></h4><p><a href="https://github.com/Luca0508/photoEditor">GitHub - Luca0508/photoEditor</a></p><h4>Link:</h4><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/95-%E7%85%A7%E7%89%87%E7%B7%A8%E8%BC%AF-app-335ef37cc707">#95 照片編輯 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/%E9%A1%AF%E7%A4%BA%E8%AD%A6%E5%91%8A%E8%A8%8A%E6%81%AF%E5%92%8C%E9%81%B8%E5%96%AE%E7%9A%84-uialertcontroller-a7548b606eea">顯示警告訊息和選單的 UIAlertController</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-uigraphicsimagerenderer-%E5%B0%87-view-%E8%AE%8A%E6%88%90%E5%9C%96%E7%89%87-41d00c568903">利用 UIGraphicsImageRenderer 將 view 變成圖片(包含只擷取 view 的部分區塊）</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/%E4%BD%9C%E6%A5%AD-49-%E7%85%A7%E7%89%87%E7%B7%A8%E8%BC%AFapp-66325d07189e">作業#49 照片編輯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%E6%95%99%E5%AE%A4/protocol-delegate%E7%B7%B4%E7%BF%92-%E7%85%A7%E7%89%87%E7%B7%A8%E8%BC%AFapp-39ee55376bf1">Protocol&amp;Delegate練習｜照片編輯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-scroll-view-%E7%B8%AE%E6%94%BE%E5%9C%96%E7%89%87-72960fb1b332">利用 scroll view &amp; contentInset 縮放置中圖片</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=657de763763b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E7%85%A7%E7%89%87%E7%B7%A8%E8%BC%AF-app-657de763763b">照片編輯 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>