<?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 Jason Chen on Medium]]></title>
        <description><![CDATA[Stories by Jason Chen on Medium]]></description>
        <link>https://medium.com/@purplvampire?source=rss-a0d057084ecd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YkJl2_xMCjlXtcin</url>
            <title>Stories by Jason Chen on Medium</title>
            <link>https://medium.com/@purplvampire?source=rss-a0d057084ecd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:44:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@purplvampire/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[用Unity做遊戲(1)-仿黑白妹2]]></title>
            <link>https://medium.com/@purplvampire/%E7%94%A8unity%E5%81%9A%E9%81%8A%E6%88%B2-1-%E4%BB%BF%E9%BB%91%E7%99%BD%E5%A6%B92-e615ae51cc31?source=rss-a0d057084ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/e615ae51cc31</guid>
            <category><![CDATA[unity-game-development]]></category>
            <dc:creator><![CDATA[Jason Chen]]></dc:creator>
            <pubDate>Sun, 15 Dec 2024 05:00:26 GMT</pubDate>
            <atom:updated>2024-12-15T05:00:26.796Z</atom:updated>
            <content:encoded><![CDATA[<p>最近在台灣遊戲社群中爆火的獨立自製遊戲有兩款, 一款是武俠遊戲活俠傳, 另一款是日本小黃油黑白妹2, 由於黑白妹2就是俗稱的簡報式遊戲, 開發學習難度低, 所以就以此作品為基礎練習Unity開發, 這邊不會有任何瑟瑟圖片, 僅做為程式開發的練習心得。</p><p>Steam遊戲介紹</p><p><a href="https://store.steampowered.com/app/2429860/_/?l=tchinese&amp;curator_clanid=43109080">Living With Sister: Monochrome Fantasy on Steam</a></p><p>今天要練習的是進度條-圖片中白色一排的部分</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBAqqJZvOA8CnEh4pxoqwQ.jpeg" /></figure><p>如上圖, 左側新增的ProgressManager物件, 在裡面建立新的Panel, 然後用一個空的物件存放6張空白的Image</p><p>接著建立一個程式腳本名稱同ProgressManager, 拉進去同名的物件中</p><p>接著我們開始撰寫腳本, 這次主要是練習StartCoroutine的功能</p><pre>using System.Collections;<br>using UnityEngine;<br>using UnityEngine.UI;<br><br>public class ProgressManager : MonoBehaviour<br>{ <br>    public GameObject pgObject;<br>    public Image[] pgImages;<br><br>    void Update() <br>    {<br>        if (pgObject != null &amp;&amp; pgObject.activeSelf == true)<br>        {<br>            StartCoroutine(SetProgress());<br>        }<br>    }<br>    IEnumerator SetProgress()<br>    {<br>        foreach (var pgImage in pgImages)<br>        {<br>            pgImage.color = new Color32(34,7,7,255);<br>            yield return new WaitForSeconds(1.0f);<br>        }<br>        pgObject.SetActive(false);<br><br>    }<br>}</pre><p>這裡面我們先建立兩個變數pgObject跟pgImages, 然後把相關物件拉進去變數中, 用來做後續處理</p><p>接著是建立一組IEnumerator函式, 來排程執行函式的內容, 有關StartCoroutine的操作概念可參考下方連結</p><p><a href="https://ithelp.ithome.com.tw/articles/10272889">26.unity打字機(StartCoroutine) — iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></p><p>該函式內容簡單說就是把清單中的物件每隔1秒鐘跑一遍, 然後把顏色改掉這樣。</p><p>最後是放入Update函式中, 當pgObject被啟用時就會觸發進度條。</p><p>腳本的UI配置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*XMPN3-C8Y4ANFbpCxJmEsQ.jpeg" /></figure><p>測試結果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qSX4_YPFpa1CRUQ7NG6Kfg.jpeg" /></figure><p>考量到進度條使用上的重複性, 也可以放到Prefabs內, 再依照不同情境去調整進度條的樣式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZrHMtNKpFRclu0qQ5AcgQ.jpeg" /></figure><p>範例</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_KrdlLsM2CjERc4tl57rA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e615ae51cc31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#39 實作IAP內購功能]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/%E5%AF%A6%E4%BD%9Ciap%E5%85%A7%E8%B3%BC%E5%8A%9F%E8%83%BD-52293baea6f7?source=rss-a0d057084ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/52293baea6f7</guid>
            <dc:creator><![CDATA[Jason Chen]]></dc:creator>
            <pubDate>Sun, 11 Feb 2024 07:26:48 GMT</pubDate>
            <atom:updated>2024-02-14T12:09:31.294Z</atom:updated>
            <content:encoded><![CDATA[<p>開發的產品經過上架後，決定實作IAP功能，讓自己的產品能夠依照不同程度族群的需求提供各種程度的服務，第一個實作的功能是去廣告。</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%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E5%BE%9E%E9%9B%B6%E9%96%8B%E5%A7%8B%E9%96%8B%E7%99%BC-ios-app-%E7%9A%84-in-app-purchase-iap-45250cf2174">從零開始開發 iOS App 的 in app purchase (IAP)</a></li><li><a href="https://franksios.medium.com/ios-app%E5%85%A7%E8%B3%BC%E5%8A%9F%E8%83%BD-in-app-purchase-6286a71105e2">IAP (In-App Purchase) 內購功能</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/%E6%96%B0%E5%A2%9E-sandbox-%E7%9A%84-test-user-%E6%B8%AC%E8%A9%A6-in-app-purchase-689c097e451e">新增 Sandbox 的 tester 測試 in app purchase</a></li></ul><p>這邊簡單摘要一下IAP實作上的流程，前提是你已經是開發者會員</p><ol><li>完成付費App協議</li><li>完成沙盒測試帳號設定</li><li>設定好內購項目與內容</li><li>實作內購功能與模型</li><li>內購功能測試</li><li>包版送審</li></ol><p>前面兩個就跳過不說，請參考上方連結，從第3點開始，會開始有些不同，也是新手特別要注意的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yk0HdNb39SKPhAL8jJ-QIA.png" /><figcaption>完成付費協議</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyj2skJB8NwWwhhFqvWWHg.png" /><figcaption>設定沙盒帳號</figcaption></figure><p>現在App Store Connect將訂閱制直接從內購功能中拆出來，所以在內購項目中只能選擇&quot;消耗性產品&quot;與&quot;非消耗性產品&quot;，而&quot;自動續訂&quot;與&quot;非續訂&quot;放到訂閱項目中設定，除此之外的設定流程都跟上方連結相同，不再贅述。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lM6Vp4ZR5jQpdlnxVPfIA.png" /><figcaption>內購項目</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dT4S8CTcUxHNGQHhXVn5-Q.png" /><figcaption>訂閱項目</figcaption></figure><p>實作內購功能上注意需要配置的項目，本次僅以非耗損性產品為例</p><ol><li>自訂IAP方法，用Singleton Pattern來呼叫裡面的function，包含抓App Store Connect設定的內購項目與執行購買，或是回復已購買產品，並將已購買的資訊保存在UserDefault內。</li><li>交易代理人，用來監控交易的結果</li><li>內購代理人，用來處理從App Store Connect抓下來的內購資訊</li><li>內購清單</li><li>用UserDefault來存放已購買的key</li><li>用Bool值變數比對UserDefault來判斷是否購買某產品，決定開啟或關閉某項功能</li></ol><p>自訂IAPManager方法要繼承NSObject類別，並且要套用StoreKit SDK，透過SKProductsRequest型別的物件，去抓App Store Connect上設定好的產品資訊</p><pre>import StoreKit<br><br>// 自建內購類別<br>class IAPManager: NSObject {<br><br>    // Singleton<br>    static let shared = IAPManager()    // 呼叫自己函式<br>    var products = [SKProduct]()        // 建立內購物件<br>    fileprivate var productRequest: SKProductsRequest!<br><br>    func getProductIDs() -&gt; [String] {<br>        [&quot;com.purplvampire.NetworkConsole.monthly&quot;,<br>         &quot;com.purplvampire.NetworkConsole.removeAds&quot;<br>        ]<br>    }<br>    <br>    func getProducts() {<br>        let productIds = getProductIDs()    // 取得陣列<br>        let productIdsSet = Set(productIds) // 將陣列轉型<br>        <br>        // 從Apple Store Connect取得IAP內購資訊<br>        productRequest = SKProductsRequest(productIdentifiers: productIdsSet)<br>        productRequest.delegate = self<br>        productRequest.start()<br>    }<br>    <br>    // 支付內購<br>    func buy(product: SKProduct) {<br>        <br>        // 先確認是否能購買商品，再執行支付程序<br>        if SKPaymentQueue.canMakePayments() {<br>            // 執行支付程序<br>            let payment = SKPayment(product: product)<br>            SKPaymentQueue.default().add(payment)<br>        } else {<br>            assertionFailure(&quot;Fail purchase!&quot;)<br>        }<br>    }<br>    <br>    // 回復已購買狀態<br>    func restore() {<br>        SKPaymentQueue.default().restoreCompletedTransactions()<br>        <br>    }<br>    <br>    // 將完成交易的值存在雲端或本機<br>    func savePurchasedItemKey() {<br>        <br>        #if USE_ICLOUD_STORAGE<br>        let storage = NSUbiquitousKeyValueStore.default<br>        #else<br>        let storage = UserDefaults.standard<br>        #endif<br>        <br>        storage.set(true, forKey: &quot;removeAds&quot;)<br>    }<br>    <br>}</pre><p>接著針對代理人productRequest.delegate = self 的部分要進行一些資訊處理，因為抓取資訊是在背景執行，如果抓下來的資料要放到TableView，那麼資料要轉到Main Thread執行緒上處理</p><pre>// 處理取到的內購資訊<br>extension IAPManager: SKProductsRequestDelegate {<br>    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {<br>        // 將資料印出<br>        response.products.forEach {<br>            print($0.localizedTitle, $0.price, $0.localizedDescription)<br>        }<br>        // 將資料轉存，配合UI更新要切到Main Thread<br>        DispatchQueue.main.async {<br>            self.products = response.products<br>        }<br>    }<br>}</pre><p>再來是針對購買行為的監控與處理，SKPaymentTransactionObserver主要是在SKPaymentQueue.default()這個方法被觸發時執行</p><pre>// 監控交易狀態<br>extension IAPManager: SKPaymentTransactionObserver {<br>    <br>    // 交易狀態改變時觸發<br>    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {<br>        <br>        transactions.forEach {<br>            <br>            print($0.payment.productIdentifier, $0.transactionState.rawValue)<br>            <br>            // 購買或失敗要做結清的動作finishTransaction($0)<br>            switch $0.transactionState {<br>            <br>            case .purchasing:<br>                break<br>            case .purchased:<br>                SKPaymentQueue.default().finishTransaction($0)<br>                self.savePurchasedItemKey()<br>                <br>            case .failed:<br>                print($0.error ?? &quot;&quot;)<br>                // 當失敗的原因不是取消交易時跳出告警<br>                if ($0.error as? SKError)?.code != .paymentCancelled {<br>                    // show error alert<br><br>                }<br>                SKPaymentQueue.default().finishTransaction($0)<br>                <br>            // 回復已購買商品<br>            case .restored:<br>                SKPaymentQueue.default().finishTransaction($0)<br>                self.savePurchasedItemKey()<br>                <br>            case .deferred:<br>                break<br>            @unknown default:<br>                break<br>            }<br>            <br>        }<br>        <br>    }<br>    <br>}</pre><p>另外在AppDelegate也要配置交易監控，並且在App生命週期停止時一併結束監控</p><pre>//<br>//  AppDelegate.swift<br>//  NetworkConsole<br><br>import UIKit<br>import StoreKit<br><br>@main<br>class AppDelegate: UIResponder, UIApplicationDelegate {<br>    <br>    fileprivate var hasRegisterForNotification: Bool = false<br><br>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br><br>        // 啟動時將IAPManager設為SKPaymentQueue的observer<br>        SKPaymentQueue.default().add(IAPManager.shared)<br>        hasRegisterForNotification = true<br>        <br>        return true<br>    }<br>    <br>    // App終止時停止SKPaymentQueue的observer<br>    func applicationWillTerminate(_ application: UIApplication) {<br>        <br>        if hasRegisterForNotification {<br>            SKPaymentQueue.default().remove(IAPManager.shared)<br>        }<br>        <br>    }<br>}</pre><p>完成IAPManage內購方法後，接著就是將內購功能部署到ViewController的按鈕Function上，這部分因為彼得潘的範例是SwiftUI，所以藉助ChatGPT的幫助改成Swift的程式碼，再進行改寫</p><p><a href="https://github.com/AppPeterPan/IAPDemo?source=post_page-----45250cf2174--------------------------------">GitHub - AppPeterPan/IAPDemo</a></p><p>上方是SwiftUI的程式碼, 請轉成UIKit的程式碼：</p><pre>import UIKit<br><br>class ProductListViewController: UIViewController {<br>    <br>    let iapManager = IAPManager.shared<br>    var tableView: UITableView!<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        setupTableView()<br>        setupNavigationBar()<br>        iapManager.getProducts()<br>    }<br>    <br>    private func setupTableView() {<br>        tableView = UITableView(frame: view.bounds, style: .plain)<br>        tableView.delegate = self<br>        tableView.dataSource = self<br>        tableView.register(UITableViewCell.self, forCellReuseIdentifier: &quot;Cell&quot;)<br>        view.addSubview(tableView)<br>    }<br>    <br>    private func setupNavigationBar() {<br>        navigationItem.title = &quot;Taylor Swift&quot;<br>        navigationItem.rightBarButtonItem = UIBarButtonItem(title: &quot;Restore&quot;, style: .plain, target: self, action: #selector(restoreTapped))<br>    }<br>    <br>    @objc func restoreTapped() {<br>        iapManager.restore()<br>    }<br>}<br><br>extension ProductListViewController: UITableViewDataSource, UITableViewDelegate {<br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        return iapManager.products.count<br>    }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;Cell&quot;, for: indexPath)<br>        let product = iapManager.products[indexPath.row]<br>        cell.textLabel?.text = product.localizedTitle<br>        cell.detailTextLabel?.text = product.regularPrice ?? &quot;&quot;<br>        return cell<br>    }<br>    <br>    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>        let product = iapManager.products[indexPath.row]<br>        iapManager.buy(product: product)<br>    }<br>}</pre><p>套用到SettingsVC中的按鈕function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8QdPPxFfikeYw9Q74v1xw.png" /><figcaption>IBOutlet配置</figcaption></figure><p>SettingsVC程式碼實作，按鈕完成購買程序後會存一筆key到UserDefault內，這個key值會被用來判斷是否觸發某項／某些功能。</p><pre>import UIKit<br>import StoreKit     // App評分&amp;購買<br><br>class SettingsTableViewController: UITableViewController {<br><br>    override func viewWillAppear(_ animated: Bool) {<br>        IAPManager.shared.getProducts() // 取得內購資訊<br>    }<br><br>    // 這個function用來判斷是否已購買商品,參數值預設false表示尚未購買,在didSelectRowAt中呼叫<br>    func removeAds(hasPurchased: Bool = false) {<br>        <br>        // 若已經購買則跳告警通知<br>        if hasPurchased {<br>            // message為多語系設定<br>            let message = NSLocalizedString(&quot;settingsVC.purchasedMsg&quot;, comment: &quot;This function has purchased.&quot;)<br>            let alertVC = UIAlertController(title: nil, message: message, preferredStyle: .alert)<br>            let okAction = UIAlertAction(title: &quot;OK&quot;, style: .default)<br>            alertVC.addAction(okAction)<br>            <br>            present(alertVC, animated: true)<br>            <br>        // 若還沒購買則進入購買程序<br>        } else {<br>            let products: [SKProduct] = IAPManager.shared.products<br>            // 購買商品<br>            let removeAds = products[1]<br>            IAPManager.shared.buy(product: removeAds)<br>        }<br>    }<br><br>    // 回復已購項目<br>    func restorePurchased() {<br>        <br>        IAPManager.shared.restore()<br>    }<br><br><br>    // MARK: - Table view data source<br><br>    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>        print(indexPath)<br>        switch indexPath {<br>        case [1,4]:<br>            print(&quot;Purchase&quot;)<br>            #if USE_ICLOUD_STORAGE<br>            let storage = NSUbiquitousKeyValueStore.default<br>            #else<br>            let storage = UserDefaults.standard<br>            #endif<br>            <br>            let removeAds = storage.bool(forKey: &quot;removeAds&quot;)<br>            self.removeAds(hasPurchased: removeAds)<br>            <br>        case [1,5]:<br>            print(&quot;Restore&quot;)<br>            self.restorePurchased()<br>        default:<br>            print(&quot;none&quot;)<br>        }<br>        // 點擊cell後取消選取<br>        self.tableView.deselectRow(at: indexPath, animated: true)<br>    }<br><br>}</pre><p>接著到含有廣告的VC下新增條件式決定是否啟用廣告</p><pre>import UIKit<br>import GoogleMobileAds<br>import AppTrackingTransparency<br>import AdSupport<br><br><br>class Console2ViewController: UIViewController, GADBannerViewDelegate {<br>    <br>    var bannerView: GADBannerView?  // 橫幅廣告<br>    var removeAds: Bool = false     // 判斷是否要移除廣告<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        // 購買項目確認,key優先存在iCloud,若沒有則存到UserDefault中<br>        #if USE_ICLOUD_STORAGE<br>        let storage = NSUbiquitousKeyValueStore.default<br>        #else<br>        let storage = UserDefaults.standard<br>        #endif<br>        <br>        removeAds = storage.bool(forKey: &quot;removeAds&quot;)  // 若key有存在則為True<br><br>        // Admob<br>        if #available(iOS 14, *) {<br>            // 請求IDFA廣告識別碼<br>            ATTrackingManager.requestTrackingAuthorization { status in<br>                <br>                if status == .authorized {<br><br>                } else {<br><br>                }<br>                // 置入廣告前先判斷有無購買決定是否移除廣告<br>                if self.removeAds == false {<br>                    // 置入廣告<br>                    DispatchQueue.main.async {<br>                        self.bannerView = GADBannerView(adSize: GADAdSizeBanner)<br>                        self.bannerView?.translatesAutoresizingMaskIntoConstraints = false<br>                        // 設定廣告單元編號<br>                        // self.bannerView?.adUnitID = &quot;ca-app-pub-3940256099942544/2934735716&quot; // 測試用<br>                        self.bannerView?.adUnitID = &quot;ca-app-pub-5052077476353721/&quot;<br>                        self.bannerView?.delegate = self<br>                        self.bannerView?.rootViewController = self<br>                        self.bannerView?.load(GADRequest())<br>                    }<br>                } <br>            }<br>        }<br>        <br>    }<br>}</pre><p>到這邊就完成實作的程序，接著就是驗證跟上架，注意要用沙盒的帳號來進行內購測試，請見Peter的文章。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NTHgQMJimuCLgoTAQgCTg.png" /><figcaption>沙盒測試</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cioIJyxiQS5IndhwxSHENw.png" /><figcaption>完成交易</figcaption></figure><p>最後就是上傳測試畫面與說明送審，只要審過就可以讓用戶購買App內的商品了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0BTiZQcoCztC37DXQjlfg.png" /><figcaption>送審資訊</figcaption></figure><p>這是我用來實作的上架App，有興趣可以下載參考</p><p><a href="https://apps.apple.com/us/app/bluetooth-console/id6465072522">‎Bluetooth Console</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52293baea6f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/%E5%AF%A6%E4%BD%9Ciap%E5%85%A7%E8%B3%BC%E5%8A%9F%E8%83%BD-52293baea6f7">#39 實作IAP內購功能</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[#38 實作iBeacon發設器]]></title>
            <link>https://medium.com/@purplvampire/38-%E5%AF%A6%E4%BD%9Cibeacon%E7%99%BC%E8%A8%AD%E5%99%A8-4f2e49a5d68?source=rss-a0d057084ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f2e49a5d68</guid>
            <dc:creator><![CDATA[Jason Chen]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 03:31:27 GMT</pubDate>
            <atom:updated>2023-09-01T03:33:09.409Z</atom:updated>
            <content:encoded><![CDATA[<p>這次要來用手機模擬Beacon發射器，讓手機端可以接收Beacon裝置發送的訊號</p><p>蘋果官方實作範例</p><p><a href="https://developer.apple.com/documentation/corelocation/turning_an_ios_device_into_an_ibeacon_device">Turning an iOS device into an iBeacon device | Apple Developer Documentation</a></p><p>MacOS版實作</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%B0%87-mac-%E8%AE%8A%E6%88%90-ibeacon-5d4f6942a128">將 mac 變成 iBeacon</a></p><p>手機Beacon接收實作與完整說明請參考彼得潘與Nelson的心得</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/swift-ibeacon-app-%E7%A8%8B%E5%BC%8F%E8%A8%AD%E8%A8%88-cd89f59f735b">Swift iBeacon App 程式設計</a></li><li><a href="https://chiahsien.github.io/post/ibeacon-development-in-swift/">iBeacon 的 Swift 開發筆記</a></li></ul><p>架構配置如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uTqLXLdI6PJL0EH8vncnfw.png" /></figure><p>ＵＩ佈局，兩個按鈕，一個是發送Beacon訊號，一個是停止發送。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PoLqF8330iako726JgzlIw.png" /></figure><p>由於iBeacon會需要CoreLocation與CoreBluetooth兩個SDK，需要設定隱私，CoreLocation負責實作iBeacon裝置，而CoreBluetooth則是用來發射iBeacon的藍芽訊號。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRD2XMKFEP5S5VJR6eHCMg.png" /></figure><p>第一步先設定iBeacon用的裝置資訊</p><pre>import CoreLocation     // 建立Beacon<br>import CoreBluetooth    // 發送廣播<br><br>class BeaconViewController: UIViewController, CLLocationManagerDelegate, CBPeripheralManagerDelegate {<br><br>    // Beacon Information<br>    let uuidString = &quot;BDAB3E6D-6196-4244-913F-94753F720AFC&quot;<br>    let major: CLBeaconMajorValue = 88<br>    let minor: CLBeaconMinorValue = 99<br>    var beaconRegion: CLBeaconRegion?<br>    var periphralManager: CBPeripheralManager!<br>}</pre><p>於ViewDidLoad()中建立藍芽發射器管理員，並指派代理人為控制器本身。</p><pre>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        // Do any additional setup after loading the view.<br>        periphralManager = CBPeripheralManager(delegate: self, queue: nil)<br>        <br>    }</pre><p>實作必要的藍芽發射器代理人功能，這是用來監控作為iBeacon元件的藍芽發射器是否有運作。</p><pre>    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {<br>        <br>        if peripheral.state != .poweredOn {<br>            print(&quot;BLE is not ready: \(peripheral.state.rawValue)&quot;)<br>        }<br>    }</pre><p>實作iBeacon訊號發送</p><pre>    @IBAction func StartBeacon(_ sender: Any) {<br>        <br>        let uuid = UUID(uuidString: uuidString)<br>        let bundleID = Bundle.main.bundleIdentifier<br>        <br>        beaconRegion = CLBeaconRegion(uuid: uuid!, major: major, minor: minor, identifier: bundleID!)<br>        <br>        let data = beaconRegion?.peripheralData(withMeasuredPower: nil) as? [String : Any]<br>        print(&quot;Start Advertising&quot;)<br>        periphralManager.startAdvertising(data)<br>    }</pre><p>用CLBeaconRegion將iBeacon相關資訊填入，實作中iBeacon發射器。</p><p>透過peripheralData(withMeasuredPower: nil)會將藍芽發射器訊號轉成Beacon訊號。</p><p>最後用periphralManager.startAdvertising()將Beacon訊號發送出去。</p><p>最後是設定停止訊號發送按鈕</p><pre>    @IBAction func stopAdvertising(_ sender: Any) {<br>        print(&quot;Stop Advertising&quot;)<br>        periphralManager.stopAdvertising()<br>    }</pre><p>大功告成。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f2e49a5d68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#37 實作UIActivityViewController]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/37-%E5%AF%A6%E4%BD%9Cuiactivityviewcontroller-5d7612909afe?source=rss-a0d057084ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d7612909afe</guid>
            <dc:creator><![CDATA[Jason Chen]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 08:02:18 GMT</pubDate>
            <atom:updated>2023-08-26T08:55:29.779Z</atom:updated>
            <content:encoded><![CDATA[<p>很好用的功能，可以直接把檔案包裝後匯出與轉發，廣泛應用在社交平台上，今天我們來實作這個功能。</p><p>先做一個function，用來處理選擇的cell</p><pre><br>    func callActivityVC(selectedRows: [IndexPath]) {<br>        <br>        var selectedItems: [String] = []<br>        <br>        for indexPath in selectedRows {<br>            let selectedItem = testList[indexPath.row]<br>            selectedItems.append(selectedItem)<br>        }<br>        <br>        let activityVC = UIActivityViewController(activityItems: selectedItems, applicationActivities: nil)<br>      <br>        activityVC.completionWithItemsHandler = {(activityType: UIActivity.ActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) -&gt; Void in<br>            <br>            // 失敗發送通知<br>            if let error {<br>                <br>                let alertVC = UIAlertController(title: &quot;Error&quot;, message: &quot;Error:\(error.localizedDescription)&quot;, preferredStyle: .alert)<br>                let okAction = UIAlertAction(title: &quot;OK&quot;, style: .default)<br>                alertVC.addAction(okAction)<br>                self.present(alertVC, animated: true, completion: nil)<br>                return<br>            }<br>            // 成功發送通知<br>            if completed {<br>                <br>                let alertVC = UIAlertController(title: &quot;Success&quot;, message: &quot;Share items information.&quot;, preferredStyle: .alert)<br>                let okAction = UIAlertAction(title: &quot;OK&quot;, style: .default)<br>                alertVC.addAction(okAction)<br>                self.present(alertVC, animated: true, completion: nil)<br>            }<br><br>        }<br>        self.present(activityVC, animated: true)<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%E6%95%99%E5%AE%A4/35-%E5%BB%BA%E7%AB%8B%E5%8F%AF%E5%A4%9A%E9%81%B8%E7%9A%84%E7%B7%A8%E8%BC%AF%E6%B8%85%E5%96%AE-11671215faf8">#35 建立可多選的編輯清單</a></p><p>多選的cell要先存進一個新的Array，後面才能餵給UIActivityView</p><pre>var selectedItems: [String] = []<br>        <br>for indexPath in selectedRows {<br>    let selectedItem = testList[indexPath.row]<br>    selectedItems.append(selectedItem)<br>}</pre><p>這段是生成並呼叫UIActivityViewController，生成時放入要匯出的物件</p><pre>let activityVC = UIActivityViewController(activityItems: selectedItems, applicationActivities: nil)<br>      <br>self.present(activityVC, animated: true)</pre><p>這段是處理匯出後的結果，比較特別是屬性為closure，然後closure的參數跟網路上的舊資料有差異，看起來有修改過。</p><pre>activityVC.completionWithItemsHandler = {(activityType: UIActivity.ActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) -&gt; Void in<br>    <br>    // 失敗發送通知<br>    if let error {<br>        <br>        let alertVC = UIAlertController(title: &quot;Error&quot;, message: &quot;Error:\(error.localizedDescription)&quot;, preferredStyle: .alert)<br>        let okAction = UIAlertAction(title: &quot;OK&quot;, style: .default)<br>        alertVC.addAction(okAction)<br>        self.present(alertVC, animated: true, completion: nil)<br>        return<br>    }<br>    // 成功發送通知<br>    if completed {<br>        <br>        let alertVC = UIAlertController(title: &quot;Success&quot;, message: &quot;Share items information.&quot;, preferredStyle: .alert)<br>        let okAction = UIAlertAction(title: &quot;OK&quot;, style: .default)<br>        alertVC.addAction(okAction)<br>        self.present(alertVC, animated: true, completion: nil)<br>    }<br><br>}</pre><p>接著到ViewDidLoad()中建立一個選單按鈕，按下後就可以呼叫匯出功能。</p><pre><br>// 設定選單按鈕<br>self.functionBtn.menu = UIMenu(children: [<br>  UIAction(title: &quot;Export to&quot;,<br>           image: UIImage(systemName: &quot;rectangle.portrait.and.arrow.forward&quot;),<br>           handler: { [self] action in<br>               if let selectedRows = tableView.indexPathsForSelectedRows {<br>                   // Call ActivityVC to export files.<br>                   self.callActivityVC(selectedRows: selectedRows)<br>               }<br>               <br>           })<br>  <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%E6%95%99%E5%AE%A4/34-%E5%9C%A8barbuttonitem%E4%B8%8A%E5%AF%A6%E4%BD%9Cpull-down-button%E9%81%B8%E5%96%AE-menu-%E6%8C%89%E9%88%95-39f2729ac479">#34 在BarButtonItem上實作Pull Down Button選單(menu)按鈕</a></p><p>成果展示，要注意實機跟模擬器環境顯示出來的有差，完整的匯出功能要在實機上測，這邊只展示模擬環境。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*5wmlDelurI0uXkI6wLa0Vg.gif" /></figure><p>覺得不錯請不吝給我掌聲喔</p><p>其他參考資料</p><ul><li><a href="https://www.appcoda.com.tw/social-framework-introduction/">初學者指南：使用社交框架與 UIActivityViewController</a></li><li><a href="https://zhongwei0717.medium.com/ios-%E7%9A%84%E5%8E%9F%E7%94%9F%E5%88%86%E4%BA%AB-uiactivityviewcontroller-f73d272dc2a3">iOS 的原生分享， UIActivityViewController</a></li><li><a href="https://jjeremy-xue.medium.com/swift-%E7%8E%A9%E7%8E%A9-uiactivityviewcontroller-5995bb80ff68">Swift — 玩玩 UIActivityViewController</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d7612909afe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/37-%E5%AF%A6%E4%BD%9Cuiactivityviewcontroller-5d7612909afe">#37 實作UIActivityViewController</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#36 實作App評價視圖]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/36-%E5%AF%A6%E4%BD%9Capp%E8%A9%95%E5%83%B9%E8%A6%96%E5%9C%96-6613156b5184?source=rss-a0d057084ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6613156b5184</guid>
            <dc:creator><![CDATA[Jason Chen]]></dc:creator>
            <pubDate>Mon, 21 Aug 2023 12:40:30 GMT</pubDate>
            <atom:updated>2023-08-22T05:00:26.283Z</atom:updated>
            <content:encoded><![CDATA[<p>利用SKStoreReviewController可以呼叫評價視圖</p><p>參考官方文件與範例</p><p><a href="https://developer.apple.com/documentation/storekit/requesting_app_store_reviews">Requesting App Store reviews | Apple Developer Documentation</a></p><p>網友文章，不過部分設定已失效</p><p><a href="https://www.jianshu.com/p/cfa3036bf428">在iOS App上使用SKStoreReviewController直接弹出评论页面</a></p><p>簡單實作一下，先在ViewControoler設置呼叫評價視圖的function</p><pre>import StoreKit<br>   <br>   func requestAppReview() {<br>        if #available(iOS 14.0, *) {<br>            if let windowScene = UIApplication.shared.windows.first?.windowScene {<br>                // 呼叫評分提示<br>                SKStoreReviewController.requestReview(in: windowScene)<br>            }<br>        } else {<br>            print(&quot;old version&quot;)<br>        }<br>    }</pre><p>然後放到按鈕內，大功告成</p><pre><br>    @IBAction func ratingApp(_ sender: UIButton) {<br><br>        requestAppReview()<br>    }</pre><p>展示</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*ARxGSy1PbfP8KBnDHoOXIw.gif" /></figure><p>蘋果的範例中還有另一種方式，就是直接呼叫App評分網址，透過網頁呼叫。</p><pre><br>    @IBAction func ratingApp(_ sender: UIButton) {<br>        // 1.手動跳到網站評價<br>        // Note: Replace the placeholder value below with the App Store ID for your app.<br>        //       You can find the App Store ID in your app&#39;s product URL.<br>        guard let writeReviewURL = URL(string: &quot;https://apps.apple.com/tw/app/&lt;AppName&gt;/id&lt;AppID&gt;?action=write-review&quot;)<br>        else { fatalError(&quot;Expected a valid URL&quot;) }<br>        UIApplication.shared.open(writeReviewURL, options: [:], completionHandler: nil)<br><br>    }</pre><p>覺得不錯請幫我鼓掌，謝謝。</p><p>實作範例</p><p><a href="https://github.com/purplvampire/Rating-My-App.git">GitHub - purplvampire/Rating-My-App</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6613156b5184" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/36-%E5%AF%A6%E4%BD%9Capp%E8%A9%95%E5%83%B9%E8%A6%96%E5%9C%96-6613156b5184">#36 實作App評價視圖</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#35 建立可多選的編輯清單]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/35-%E5%BB%BA%E7%AB%8B%E5%8F%AF%E5%A4%9A%E9%81%B8%E7%9A%84%E7%B7%A8%E8%BC%AF%E6%B8%85%E5%96%AE-11671215faf8?source=rss-a0d057084ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/11671215faf8</guid>
            <dc:creator><![CDATA[Jason Chen]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 12:50:30 GMT</pubDate>
            <atom:updated>2023-08-19T14:12:25.262Z</atom:updated>
            <content:encoded><![CDATA[<p>有時候我們會需要同時處裡複數的表格，包含刪除或轉發</p><p>建立流程</p><ol><li>啟用allowsMultipleSelectionDuringEditing</li><li>設定系統內建的編輯按鈕function，只有在編輯模式下才啟用多選功能</li><li>編輯shouldPerformSegue，在多選時點擊Cell不跳到下一頁</li></ol><p>步驟一、在viewDidLoad內建立在NavigationBar新增編輯按鈕，並啟用allowsMultipleSelectionDuringEditing。</p><pre>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.<br>        self.navigationItem.leftBarButtonItem = self.editButtonItem<br>        <br>        self.tableView.allowsMultipleSelectionDuringEditing = true<br>    }</pre><p>步驟二、呼叫setEditing編輯function，按下編輯按鈕時會切換成編輯模式，預設是刪除模式，但設定allowsMultipleSelectionDuringEditing後會變成多選模式，如果有設定moveRowAt()則會增加調整排列的模式。</p><pre> <br>    override func setEditing(_ editing: Bool, animated: Bool) {<br>        super.setEditing(editing, animated: animated)<br>        self.tableView.setEditing(editing, animated: true)<br>        <br>    }</pre><p>步驟三、判斷在一般模式下點擊cell才跳下一頁</p><pre><br>    override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -&gt; Bool {<br>        if self.tableView.isEditing {<br>           return false<br>        }<br>        return true<br>    }</pre><p>最後再設定模擬測試環境</p><pre>    // MARK: - Table view data source<br><br>    override func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        // #warning Incomplete implementation, return the number of sections<br>        return 1<br>    }<br><br>    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        // #warning Incomplete implementation, return the number of rows<br>        return 4<br>    }<br><br>    <br>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;myCell&quot;, for: indexPath)<br><br>        // Configure the cell...<br>        cell.textLabel?.text = &quot;Test&quot;<br><br>        return cell<br>    }</pre><p>接著我們就可以開始測試了，布局如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-ORxMT_TwqwXKoBqhl-Lg.png" /></figure><p>成果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*Oxrd0_5HeqiHsiE1OW7wdQ.gif" /></figure><p>範例</p><p><a href="https://github.com/purplvampire/MultiChoice.git">GitHub - purplvampire/MultiChoice</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11671215faf8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/35-%E5%BB%BA%E7%AB%8B%E5%8F%AF%E5%A4%9A%E9%81%B8%E7%9A%84%E7%B7%A8%E8%BC%AF%E6%B8%85%E5%96%AE-11671215faf8">#35 建立可多選的編輯清單</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#34 在BarButtonItem上實作Pull Down Button選單(menu)按鈕]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/34-%E5%9C%A8barbuttonitem%E4%B8%8A%E5%AF%A6%E4%BD%9Cpull-down-button%E9%81%B8%E5%96%AE-menu-%E6%8C%89%E9%88%95-39f2729ac479?source=rss-a0d057084ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/39f2729ac479</guid>
            <dc:creator><![CDATA[Jason Chen]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 12:21:00 GMT</pubDate>
            <atom:updated>2023-08-19T14:12:05.269Z</atom:updated>
            <content:encoded><![CDATA[<p>參考彼得潘的文章，改成在BarButtonItem上實作Pull Down Button</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-%E7%9A%84%E9%81%B8%E5%96%AE-menu-%E6%8C%89%E9%88%95-pull-down-button-pop-up-button-2ddab2181ee5">iOS 的選單(menu)按鈕 — Pull Down Button &amp; Pop Up Button</a></p><p>首先用程式建立好一個BarButtonItem</p><pre> override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Do any additional setup after loading the view.<br>        <br>        let menuButtonItem = UIBarButtonItem(systemItem: .trash)<br>    }</pre><p>接著在menu屬性中建立子物件，這邊不用showsMenuAsPrimaryAction，你也沒得選</p><pre><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Do any additional setup after loading the view.<br>        <br>        let menuButtonItem = UIBarButtonItem(systemItem: .trash)<br>        <br>        menuButtonItem.menu = UIMenu(children: [<br>            UIAction(title: &quot;Select Messages&quot;, image: UIImage(systemName: &quot;checkmark.circle&quot;), handler: { action in<br>                print(&quot;Select Message&quot;)<br>                }),<br>            UIAction(title: &quot;Edit Pins&quot;, image: UIImage(systemName: &quot;pin&quot;)) { action in<br>                print(&quot;Edit Pins&quot;)<br>                },<br>            UIAction(title: &quot;Edit Name and Photo&quot;, image: UIImage(systemName: &quot;person.crop.circle&quot;), handler: { action in<br>                print(&quot;Edit Name and Photo&quot;)<br>            })<br>        ])<br><br><br><br>    }</pre><p>最後放到NavigationItem內</p><pre><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        // ... Create BarButtionItem and Pull Down Menu ...<br>        <br>        self.navigationItem.rightBarButtonItem = menuButtonItem<br><br>    }</pre><p>成果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*Zqvryrj_0vMG1iUi22SriQ.gif" /></figure><p>Github原始碼參考</p><p><a href="https://github.com/purplvampire/MenuButton.git">GitHub - purplvampire/MenuButton</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39f2729ac479" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/34-%E5%9C%A8barbuttonitem%E4%B8%8A%E5%AF%A6%E4%BD%9Cpull-down-button%E9%81%B8%E5%96%AE-menu-%E6%8C%89%E9%88%95-39f2729ac479">#34 在BarButtonItem上實作Pull Down Button選單(menu)按鈕</a> was originally published in <a href="https://medium.com/peter-pan-swift-ios-class">彼得潘的 Swift iOS / Flutter App 開發教室</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#33 利用 notification center 在 controller 間傳資料]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/33-%E5%88%A9%E7%94%A8-notification-center-%E5%9C%A8-controller-%E9%96%93%E5%82%B3%E8%B3%87%E6%96%99-510c7bf51be7?source=rss-a0d057084ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/510c7bf51be7</guid>
            <dc:creator><![CDATA[Jason Chen]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 04:01:41 GMT</pubDate>
            <atom:updated>2023-08-18T06:39:12.101Z</atom:updated>
            <content:encoded><![CDATA[<p>在設定視圖中調整其他視圖內Label的字型大小</p><p>本次作業會使用到以下技術</p><ol><li>用來傳遞異動訊息的notification center</li><li>用來存取字型大小數值的UserDefault</li><li>以Singleton Design Pattern來統一處理字型大小變更的Extension型別</li><li>用IBOutletCollection統一變更視圖內的Label大小</li></ol><p>佈局</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0izbfYj-XzaCyfEBPVLfA.png" /></figure><p>先設置字型大小與Slider拉桿異動後的位置數值存取，分別做成set與get方法用來存取UserDefault內的值，因為UIFont只吃CGFloat，所以回傳值要做轉型。</p><pre><br>class UserDefaultsManager {<br>    // Singleton<br>    static let shared = UserDefaultsManager()<br>    private init() {}<br>    <br>    // UserDefault的Key,避免使用Hardcode<br>    private let fontSizekey = &quot;fontSizekey&quot;<br>    private let sliderValuekey = &quot;sliderValuekey&quot;<br>    <br>    // 存取各視圖內Label所需的字型大小<br>    func getFontSize() -&gt; CGFloat {<br>        let savedFontSize = UserDefaults.standard.float(forKey: fontSizekey)<br>        return CGFloat(savedFontSize &gt; 0 ? savedFontSize : 17)<br>    }<br>    <br>    func setFontSize(_ size: Float) {<br>        UserDefaults.standard.set(size, forKey: fontSizekey)<br>    }<br>    // 存取設定視圖內Slider拉桿的位置<br>    func getSliderValue() -&gt; Float? {<br>        let savedSliderValue = UserDefaults.standard.float(forKey: sliderValuekey)<br>        return savedSliderValue<br>    }<br>    <br>    func setSliderValue(_ value: Float) {<br>        UserDefaults.standard.set(value, forKey: sliderValuekey)<br>    }<br>    <br>}</pre><p>接著在設定ViewController內新增notification center的延伸型別，主要是避免發送訊息時打錯字。</p><pre><br>// 程式的通知中心<br>extension Notification.Name {<br>    static let doRefreshNotification = Notification.Name(&quot;doRefreshNotification&quot;)<br>}</pre><p>在Slider的IBAction中寫一段程式碼，用來存放拉桿的值，然後透過notification center發送廣播訊息到其他視圖。</p><pre> <br>    @IBAction func adjustFontSize(_ sender: UISlider) {<br>        <br>        sender.value.round()    // 捨棄小數點值<br><br>        UserDefaultsManager.shared.setFontSize(sender.value + 17)<br>        UserDefaultsManager.shared.setSliderValue(sender.value)<br>        <br>        let fontSize = UserDefaultsManager.shared.getFontSize()<br>        <br>        self.customLabelFont(size: fontSize)<br><br>        NotificationCenter.default.post(name: .doRefreshNotification, object: nil)  // 程式的通知中心<br><br>    }</pre><p>設定視圖內統一用一個function來處理不同的Lable大小，然後用forloop處理IBOutletCollection的FontSize。</p><pre>    func customLabelFont(size fontSize: CGFloat) {<br>        <br>        for label in cloudLabels {<br>            label.font = UIFont.systemFont(ofSize: fontSize)<br>        }<br>        sampleFontLabel.font = UIFont.systemFont(ofSize: fontSize)<br>        codeLabel.font = UIFont.systemFont(ofSize: fontSize)<br>    }</pre><p>IBOutletCollection連接如下圖，注意是Array型別。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oI51tVQSRMrxyr8Az2BywQ.png" /></figure><p>然後要在設定控制器的ViewDidLoad配置好每次進入時更新Label大小與Slider拉桿值，其他控制器只需要更新Label大小，用UserDefaultsManager讀取資料然後改變元件Font Size。</p><pre>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        updateUI()<br>    }<br><br>    func updateUI() {<br>        <br>        if let sliderValue = UserDefaultsManager.shared.getSliderValue() {<br>            <br>            fontSize.value = sliderValue  // 設定拉桿值<br>            <br>            let fontSize = UserDefaultsManager.shared.getFontSize()<br>            self.customLabelFont(size: fontSize)<br>        }<br>    }<br><br>    <br>    func customLabelFont(size fontSize: CGFloat) {<br>        <br>        for label in cloudLabels {<br>            label.font = UIFont.systemFont(ofSize: fontSize)<br>        }<br>        sampleFontLabel.font = UIFont.systemFont(ofSize: fontSize)<br>        codeLabel.font = UIFont.systemFont(ofSize: fontSize)<br>    }</pre><p>其他視圖控制器則要搭配notification center接收異動通知並更新元件Font Size，下面是TableView的設定範例。</p><pre><br>class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {<br><br>    var fontSize: CGFloat = 17  // 用來接收UserDefault的回傳值<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>        // Do any additional setup after loading the view.<br><br>        updateUI()<br>        <br>        // 觸發通知中心時自動刷新新的訊息<br>        NotificationCenter.default.addObserver(self,<br>                                               selector: #selector(updateUI),<br>                                               name: .doRefreshNotification,<br>                                               object: nil)<br>    }<br>    <br>    override func viewWillAppear(_ animated: Bool) {<br>        super.viewWillAppear(animated)<br>        updateUI()<br>    }<br>    <br>    @objc<br>    func updateUI() {<br>        self.fontSize = UserDefaultsManager.shared.getFontSize()<br>        self.tableView.setCustomCellLabelFont(size: fontSize)<br>    }<br>}<br><br>extension UITableView {<br>    <br>    func setCustomCellLabelFont(size: CGFloat) {<br>        let labelAppearanceProxy = UILabel.appearance(whenContainedInInstancesOf: [UITableViewCell.self])<br>        labelAppearanceProxy.font = UIFont.systemFont(ofSize: size)<br>    }<br>    <br>}</pre><p>成果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*6LChhWcZByGchx4406JUSg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=510c7bf51be7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/33-%E5%88%A9%E7%94%A8-notification-center-%E5%9C%A8-controller-%E9%96%93%E5%82%B3%E8%B3%87%E6%96%99-510c7bf51be7">#33 利用 notification center 在 controller 間傳資料</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[#32 文字的縮放和字數 — UISlider & UITextField 的練習]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/32-%E6%96%87%E5%AD%97%E7%9A%84%E7%B8%AE%E6%94%BE%E5%92%8C%E5%AD%97%E6%95%B8-uislider-uitextfield-%E7%9A%84%E7%B7%B4%E7%BF%92-432ef9dffed8?source=rss-a0d057084ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/432ef9dffed8</guid>
            <dc:creator><![CDATA[Jason Chen]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 02:36:52 GMT</pubDate>
            <atom:updated>2023-08-18T06:37:41.179Z</atom:updated>
            <content:encoded><![CDATA[<h3>#32 文字的縮放和字數 — UISlider &amp; UITextField 的練習</h3><p>練習透過UISlider來縮放UITextField的字型大小</p><p>首先先將UITextField與UISlider元件拉好，用StackView完成佈局與約束條件設置</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aI7TE8712WBSLN__XfWG6Q.png" /><figcaption>StackView佈局與各物件的約束條件</figcaption></figure><p>接著設定UISlider的最小值，中間值與最大值，配置好兩端的圖示</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KHIuspaCeduy1K18-KzsQ.png" /><figcaption>UISlider設置</figcaption></figure><p>接著來拉IBOutlet，IBAction，分別對應UITextField與UISlider，Outlet的名稱用名詞＋物件類別名，Action名則是用動詞</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iBj95FZ3TjBS7Temfy7v1g.png" /><figcaption>拉IBOutlet與IBAction</figcaption></figure><p>最後是在IBAction中寫一段程式碼，由於Slider傳回的是Float型別，所以要轉型成CGFloat再餵入font屬性。</p><pre><br>    func updateUI(fontsize: Float) {<br>        fileTextView.font = UIFont(name: &quot;Kailasa&quot;, size: 18 + CGFloat(fontsize))<br>    }<br><br>    @IBAction func changeFontSize(_ sender: UISlider) {<br>        <br>        sender.value.round()            // 去小數點值<br>        self.fontSize = sender.value<br>        filenameLabel.text = String(fontSize)<br>        updateUI(fontsize: fontSize)    // 變更字型大小<br>    }</pre><p>成果展示</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*3-2Hzz6-n9SIPk9dfikv1A.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=432ef9dffed8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/32-%E6%96%87%E5%AD%97%E7%9A%84%E7%B8%AE%E6%94%BE%E5%92%8C%E5%AD%97%E6%95%B8-uislider-uitextfield-%E7%9A%84%E7%B7%B4%E7%BF%92-432ef9dffed8">#32 文字的縮放和字數 — UISlider &amp; UITextField 的練習</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[#31 以 static cells 模仿製作 iOS App 表格頁面]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/31-%E4%BB%A5-static-cells-%E6%A8%A1%E4%BB%BF%E8%A3%BD%E4%BD%9C-ios-app-%E8%A1%A8%E6%A0%BC%E9%A0%81%E9%9D%A2-dfb9fae4beb5?source=rss-a0d057084ecd------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfb9fae4beb5</guid>
            <dc:creator><![CDATA[Jason Chen]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 01:57:23 GMT</pubDate>
            <atom:updated>2023-08-18T06:38:51.756Z</atom:updated>
            <content:encoded><![CDATA[<p>模仿製作設定頁面</p><p>整體配置如下圖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7aVC7pWV8C9EGHGJF_WHA.png" /><figcaption>設定Static Cells且配置5個Sections</figcaption></figure><p>每個Section分別配置數量不等的cell，且表格內的物件用StackView包裝起來，配置好四邊約束條件(Constraints)。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9yolz3ZNHVlAoFA_6mWO5w.png" /><figcaption>Stack View的配置資料</figcaption></figure><p>StackView內的物件也要設定好約束條件，包含圖片跟Label的間距與佈局，另外要注意圖片除了長寬外，另外Hungging Priority也要調高，避免與Label相衝。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lBTPjv5uVPHSPPJI4EZLQ.png" /><figcaption>StackView內物件的佈局與間距設定</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*978JojkkF2dnxZHA9GYoyg.png" /><figcaption>圖片的長寬約束條件與Hugging Priority</figcaption></figure><p>另外針對不同的Cell可以選擇配置Accessory，就是在Cell右邊顯示箭頭，如果有配置按鈕的就不用設置。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jqyrhySUpWf6aWF6fYSq1Q.png" /><figcaption>配置Accessory符號</figcaption></figure><p>成果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*qbpJnvpLp9GuEL42JXT2cg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfb9fae4beb5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/31-%E4%BB%A5-static-cells-%E6%A8%A1%E4%BB%BF%E8%A3%BD%E4%BD%9C-ios-app-%E8%A1%A8%E6%A0%BC%E9%A0%81%E9%9D%A2-dfb9fae4beb5">#31 以 static cells 模仿製作 iOS 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>