<?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 Lou on Medium]]></title>
        <description><![CDATA[Stories by Lou on Medium]]></description>
        <link>https://medium.com/@hover1202?source=rss-ecffe12b9c07------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SMCgg0gUk3NefRM5o-LFzw.jpeg</url>
            <title>Stories by Lou on Medium</title>
            <link>https://medium.com/@hover1202?source=rss-ecffe12b9c07------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 14:07:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hover1202/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[#22 實作 Table View 的基本功能 -FB 頁面 part4]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part4-73ce6020809e?source=rss-ecffe12b9c07------2</link>
            <guid isPermaLink="false">https://medium.com/p/73ce6020809e</guid>
            <dc:creator><![CDATA[Lou]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 16:21:04 GMT</pubDate>
            <atom:updated>2023-07-28T14:18:46.899Z</atom:updated>
            <content:encoded><![CDATA[<p>首頁選擇照片後跳轉po文頁面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*Bv4tyzmSso6aa333AWZhgg.gif" /><figcaption>選擇照片</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spIJvz4DiyMA-0va-pmb5Q.png" /><figcaption>segue id</figcaption></figure><p>HomePageTableViewController 傳遞資料到PostViewController</p><pre>     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>         if segue.identifier == &quot;selcetPhoto&quot;,<br>            let postViewController = segue.destination as? PostViewController,<br>            let image = sender as? UIImage {<br>             postViewController.selectedImage = image<br>         }<br>     }</pre><p>PHPickerViewControllerDelegate</p><pre>import PhotosUI<br><br>extension HomePageTableViewController: PHPickerViewControllerDelegate {<br>    <br>    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {<br>        picker.dismiss(animated: true)<br><br>        guard !results.isEmpty else {<br>            // 使用者沒有選擇照片<br>            return<br>        }<br><br>        let itemProvider = results.first?.itemProvider<br><br>        if let itemProvider = itemProvider, itemProvider.canLoadObject(ofClass: UIImage.self) {<br>            itemProvider.loadObject(ofClass: UIImage.self) { [weak self] (object, error) in<br>                DispatchQueue.main.async {<br>                    if let error = error {<br>                        print(&quot;Error loading image: \(error)&quot;)<br>                        return<br>                    }<br><br>                    if let image = object as? UIImage {<br>                        // 使用 Segue 跳轉 PostViewController傳遞圖片<br>                        self?.performSegue(withIdentifier: &quot;selcetPhoto&quot;, sender: image)<br>                    }<br>                }<br>            }<br>        }<br><br>    }<br>}</pre><p>首頁點選po文欄位跳轉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*Pd6cuVav1ChyfENulXnXEw.gif" /><figcaption>進入po文頁面</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eNCpVTiMH1HrtjP8mDPyTQ.png" /></figure><blockquote>PostViewController新增貼文頁面</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgoML6G1w17wEUj4OlEL1g.png" /><figcaption>PostViewController 元件</figcaption></figure><pre>import UIKit<br>import PhotosUI<br><br>class PostViewController: UIViewController {<br>    <br>    @IBOutlet weak var userImageView: UIImageView!<br>    @IBOutlet weak var userNameLabel: UILabel!<br>    @IBOutlet weak var postTextView: UITextView!<br>    @IBOutlet weak var postImageView: UIImageView!<br>    @IBOutlet weak var stateButton: UIButton!<br>    @IBOutlet weak var addPhotoButton: UIButton!<br>    var postButton: UIButton!<br>    var isPostPublic = true // 貼文公開狀態<br>    var selectedImage: UIImage?  // 前一頁選擇的照片<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        navigationController?.hidesBarsOnSwipe = false<br>        tabBarController?.tabBar.isHidden = true<br>        postTextView.delegate = self // 代理TextView<br>        updateUI()<br>        setNavigationbar()<br>        // 使用選取的照片 更新畫面<br>        if let image = selectedImage {<br>            postImageView.image = image<br>        }<br>    }</pre><blockquote>發布貼文按鈕樣式變更(有選擇圖片會變藍色)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*0mJwQAduNhNPFGYFmGPp7A.gif" /><figcaption>按鈕樣式變更</figcaption></figure><pre>    override func viewWillAppear(_ animated: Bool) {<br>        super.viewWillAppear(animated)<br>        <br>        // 有選擇圖片 發布按鈕樣式變成藍色<br>        if selectedImage != nil {<br>            postButton.backgroundColor = UIColor(red: 23/255, green: 119/255, blue: 241/255, alpha: 1)<br>        }<br>    }</pre><blockquote>設定UI畫面</blockquote><pre>    func updateUI() {<br>        <br>        userNameLabel.text = &quot;Lou&quot;<br>        userImageView.image = UIImage(named: &quot;userphoto&quot;)<br>        stateButton.layer.borderWidth = 1<br>        stateButton.layer.borderColor = CGColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1)<br>        stateButton.layer.cornerRadius = 10<br>        stateButton.setImage(UIImage(systemName: &quot;globe.asia.australia.fill&quot;), for: .normal)<br>        stateButton.tintColor = UIColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1)<br>        stateButton.contentHorizontalAlignment = .left<br>        addPhotoButton.layer.borderWidth = 1<br>        addPhotoButton.layer.borderColor = CGColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1)<br>        addPhotoButton.layer.cornerRadius = 10<br>        <br>        // 調整間距 (檢查版本兩種寫法 消除舊版黃色警告)<br>        if #available(iOS 15.0, *) {<br>            var config = UIButton.Configuration.plain()<br>            config.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 0)<br>            stateButton.configuration = config<br>        } else {<br>            // 使用舊版的方式<br>            stateButton.contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)<br>        }<br>        <br>    }</pre><p>自訂Navigation bar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJmySRMXB8-rr5CcUSlLCg.png" /><figcaption>貼文按鈕</figcaption></figure><pre>func setNavigationbar() {<br>        // 設定左邊關閉按鈕<br>        let closeButton = UIButton(type: .system)<br>        closeButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)<br>        let closeSymbolConfig = UIImage.SymbolConfiguration(weight: .heavy)<br>        let closeImage = UIImage(systemName: &quot;xmark&quot;, withConfiguration: closeSymbolConfig)<br>        closeButton.setImage(closeImage, for: .normal)<br>        closeButton.tintColor = UIColor(red: 5/255, green: 5/255, blue: 5/255, alpha: 1)<br>        closeButton.addTarget(self, action: #selector(closeButtonTapped), for: .touchUpInside)<br>        let closeButtonItem = UIBarButtonItem(customView: closeButton)<br>        navigationItem.leftBarButtonItem = closeButtonItem<br>        <br>        // 設定右邊發文按鈕<br>        postButton = UIButton(type: .system)<br>        postButton.setTitle(&quot;發布&quot;, for: .normal)<br>        postButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .bold)<br>        postButton.backgroundColor = UIColor(red: 228/255, green: 229/255, blue: 234/255, alpha: 1)<br>        postButton.setTitleColor(UIColor(red: 1, green: 1, blue: 1, alpha: 1), for: .normal)<br>        postButton.frame = CGRect(x: 0, y: 0, width: 80, height: 40)<br>        postButton.layer.cornerRadius = 4<br>        postButton.addTarget(self, action: #selector(postButtonTapped), for: .touchUpInside)<br>        let postButtonItem = UIBarButtonItem(customView: postButton)<br>        navigationItem.rightBarButtonItem = postButtonItem<br>        <br>        // 設定標題<br>        navigationItem.title = &quot;建立貼文&quot;<br>        let attributes: [NSAttributedString.Key: Any] = [<br>            .foregroundColor: UIColor(red: 5/255, green: 5/255, blue: 5/255, alpha: 1),<br>            .font: UIFont.systemFont(ofSize: 18)<br>        ]<br>        navigationController?.navigationBar.titleTextAttributes = attributes<br>        <br>        navigationController?.navigationBar.barTintColor = UIColor(red: 247/255, green: 248/255, blue: 249/255, alpha: 1)<br>        <br>    }</pre><blockquote>新增照片按鈕</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLulDY_YQ5ykPqNv77UY5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*RFubJQaZjZmDs2Cv5RmJ6g.gif" /><figcaption>新增照片</figcaption></figure><p>PHPickerViewControllerDelegate</p><pre>import PhotosUI<br><br>extension PostViewController: PHPickerViewControllerDelegate {<br>    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {<br>        dismiss(animated: true, completion: nil)<br>        <br>        let itemProvider = results.first?.itemProvider<br>        <br>        if let itemProvider = itemProvider, itemProvider.canLoadObject(ofClass: UIImage.self) {<br>            itemProvider.loadObject(ofClass: UIImage.self) { [weak self] (image, error) in<br>                DispatchQueue.main.async {<br>                    if let image = image as? UIImage {<br>                        self?.postImageView.image = image<br>                        // 變更發布按鈕樣式<br>                        self?.postButton.backgroundColor = UIColor(red: 23/255, green: 119/255, blue: 241/255, alpha: 1)<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}<br><br><br>    // 按鈕選擇照片<br>    @IBAction func selectphoto(_ sender: Any) {<br>        var configuration = PHPickerConfiguration()<br>        configuration.filter = .images<br>        let picker = PHPickerViewController(configuration: configuration)<br>        picker.delegate = self<br>        present(picker, animated: true)<br>    }</pre><blockquote>新增文字內容</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*4fWETUXJSLGIHQUpggDQQw.gif" /></figure><p>透過UITextViewDelegate 使用TextView function</p><pre>import UIKit<br><br>extension PostViewController: UITextViewDelegate {<br>    <br>    func textViewDidChange(_ textView: UITextView) {<br>        //  發布按鈕樣式 隨著內文變更<br>        if textView.text.isEmpty {<br>            postButton.backgroundColor = UIColor(red: 228/255, green: 229/255, blue: 234/255, alpha: 1)<br>        } else {<br>            postButton.backgroundColor = UIColor(red: 23/255, green: 119/255, blue: 241/255, alpha: 1)<br>        }<br>    }<br>    <br>    func textViewDidBeginEditing(_ textView: UITextView) {<br>        // 開始打字時 文字欄變空白<br>        textView.text = &quot;&quot;<br>        textView.textColor = UIColor(red: 5/255, green: 5/255, blue: 5/255, alpha: 1)<br>    }<br>}</pre><blockquote>貼文隱私狀態按鈕 Pop Up Button</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGwCyyjP1cK6S0sh0STCrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*zxLR8N5Bqet2N6s0NTnK0w.gif" /><figcaption>Pop Up Button貼文隱私選單</figcaption></figure><p>點選 storyboard從右鍵選單點選 Open As &gt; Source Code，顯示 storyboard xml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CN7MCV60bF7rMW7szsAUIg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LO7raPlzyCUbOA6Kws2Zjg.png" /><figcaption>object id</figcaption></figure><p>定義選單功能</p><pre>@objc func selectPublic() {<br>        stateButton.setImage(UIImage(systemName: &quot;globe.asia.australia.fill&quot;), for: .normal)<br>        isPostPublic = true<br>    }<br>    <br>    @objc func selectPrivate() {<br>        stateButton.setImage(UIImage(systemName: &quot;person.2.fill&quot;), for: .normal)<br>        isPostPublic = false<br>    }</pre><p>action 的 selector 欄位設定上面定義的 function ，destination 欄位設定 controller 的 object id 3HZ-Xi-a6P，id 欄位設定一個隨機不重覆的 id</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5C3apzeLpwke23fx72hVQ.png" /></figure><p>參考如下</p><p><a href="https://medium.com/%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-swift-ios-app-%E9%96%8B%E7%99%BC%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/%E8%A8%AD%E5%AE%9A-pop-up-button-pop-down-button-%E4%B8%8B-command-%E7%9A%84-selector-557f8289a23d">設定 pop up button / pull down button 下 command 的 selector</a></p><p>發布貼文&amp;返回功能</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*l51HPatxCB_abKl5X84JwQ.gif" /><figcaption>po文</figcaption></figure><pre>@objc func postButtonTapped() {<br>        <br>        // 沒有文字或圖片 無法發布<br>        guard !(postTextView.text.isEmpty || postTextView.text == &quot;在想些什麼？&quot;) || postImageView.image != nil else {<br>            return<br>        }<br>        <br>        // 儲存圖片至app資料夾 並獲取圖片路徑<br>        if let postImage = postImageView.image,<br>           let imageData = postImage.pngData(),<br>           let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {<br>           <br>            let fileName = UUID().uuidString<br>            let fileURL = documentsDirectory.appendingPathComponent(fileName)<br>            <br>            do {<br>                try imageData.write(to: fileURL)<br>            } catch {<br>                print(&quot;Error saving image: \(error)&quot;)<br>            }<br>            <br>            // 沒有輸入文字 只儲存圖片<br>            let text = postTextView.text.isEmpty || postTextView.text == &quot;在想些什麼？&quot; ? &quot;&quot; : postTextView.text<br>            let postInfo = PostInfo(userName: &quot;Lou&quot;, profilePictureName: &quot;userphoto&quot;, timestamp: Date(), isPublic: isPostPublic, text: text, imageName: fileName)<br>            postArray.append(postInfo)<br>        } else {<br>            // 無圖片 只儲存文字<br>            let text = postTextView.text.isEmpty || postTextView.text == &quot;在想些什麼？&quot; ? &quot;&quot; : postTextView.text<br>            <br>            let postInfo = PostInfo(userName: &quot;Lou&quot;, profilePictureName: &quot;userphoto&quot;, timestamp: Date(), isPublic: isPostPublic, text: text, imageName: nil)<br>            postArray.append(postInfo)<br>        }<br>        <br>        self.navigationController?.popViewController(animated: true) //發布即跳出視窗<br>    }<br><br><br><br>    @objc func closeButtonTapped() {<br>        // 返回上一頁<br>        self.navigationController?.popViewController(animated: true)<br>    }</pre><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/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-f4e38483ec06">#22 實作 Table View 的基本功能 -FB 頁面 part1</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/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part2-12ac545edd1d">#22 實作 Table View 的基本功能 -FB 頁面 part2</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/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part3-91c9b0057571">#22 實作 Table View 的基本功能 -FB 頁面 part3</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73ce6020809e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part4-73ce6020809e">#22 實作 Table View 的基本功能 -FB 頁面 part4</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[#22 實作 Table View 的基本功能 -FB 頁面 part3]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part3-91c9b0057571?source=rss-ecffe12b9c07------2</link>
            <guid isPermaLink="false">https://medium.com/p/91c9b0057571</guid>
            <dc:creator><![CDATA[Lou]]></dc:creator>
            <pubDate>Thu, 20 Jul 2023 09:39:30 GMT</pubDate>
            <atom:updated>2023-07-27T16:21:53.733Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>ViewController+TableViewController</blockquote><p>貼文內容Container View連結TableViewController</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLYfhCdyB2Ji3aaw_MrMHw.png" /><figcaption>Container View連結TableViewController</figcaption></figure><blockquote>CommentViewController貼文頂部及留言功能</blockquote><blockquote>CommentTableViewController貼文內容及留言內容</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*OIS-Gnl2ox92_itxBczrxQ.gif" /><figcaption>點進貼文觀看留言</figcaption></figure><blockquote>CommentViewController</blockquote><p><strong>接收上一頁的資料</strong></p><p>selectSection選擇的貼文以及shouldOpenKeyboard點選貼文進入內文不會彈出鍵盤,點選留言按鈕進入內文會彈出鍵盤</p><pre>class CommentViewController: UIViewController {<br><br>    var selectSection: Int<br>    var shouldOpenKeyboard: Bool<br>    <br>    init?(coder: NSCoder, selectSection: Int, shouldOpenKeyboard: Bool ) {<br>        self.selectSection = selectSection<br>        self.shouldOpenKeyboard = shouldOpenKeyboard<br>        super.init(coder: coder)<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br><br>}</pre><p><strong>自訂Navigation bar</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*Qtyx0UKVD27QWXkZs8yv5w.png" /><figcaption>貼文者資料的<strong>Navigation bar</strong></figcaption></figure><pre>    func setNavigationbar() {<br>        // 設定左邊返回按鈕<br>        let backButton = UIButton(type: .system)<br>        backButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)<br>        let backSymbolConfig = UIImage.SymbolConfiguration(weight: .heavy)<br>        let backImage = UIImage(systemName: &quot;chevron.backward&quot;, withConfiguration: backSymbolConfig)<br>        backButton.setImage(backImage, for: .normal)<br>        backButton.tintColor = UIColor(red: 5/255, green: 5/255, blue: 5/255, alpha: 1)<br>        backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)<br>        let backButtonItem = UIBarButtonItem(customView: backButton)<br>        <br>        <br>        // 設定左邊ImageView<br>        let profilePictureImageView = UIImageView()<br>        profilePictureImageView.frame = CGRect(x: 0, y: 0, width: 44, height: 44)<br>        profilePictureImageView.image = UIImage(named: postArray[selectSection].profilePictureName)<br>        profilePictureImageView.contentMode = .scaleAspectFill<br>        profilePictureImageView.layer.cornerRadius = 22<br>        profilePictureImageView.clipsToBounds = true<br>        let profilePictureItem = UIBarButtonItem(customView: profilePictureImageView)<br>        <br>        // 貼文者資料view<br>        let container = UIView()<br>        // 發文者名稱<br>        let nameLabel = UILabel()<br>        nameLabel.text = postArray[selectSection].userName<br>        nameLabel.font = UIFont.systemFont(ofSize: 17)<br>        nameLabel.textColor = UIColor(red: 5/255, green: 5/255, blue: 5/255, alpha: 1)<br>        nameLabel.translatesAutoresizingMaskIntoConstraints = false<br>        container.addSubview(nameLabel)<br>        // 發文時間<br>        let timeLabel = UILabel()<br>        timeLabel.text = timeAgoDisplay(date: postArray[selectSection].timestamp)<br>        timeLabel.font = UIFont.systemFont(ofSize: 17)<br>        timeLabel.textColor = UIColor(red: 101/255, green: 103/255, blue: 106/255, alpha: 1)<br>        timeLabel.translatesAutoresizingMaskIntoConstraints = false<br>        container.addSubview(timeLabel)<br>        // 分隔符號<br>        let separatorLabel = UILabel()<br>        separatorLabel.text = &quot;．&quot;<br>        separatorLabel.font = UIFont(name: &quot;蘋方-繁&quot;, size: 17)<br>        separatorLabel.textColor = UIColor(red: 101/255, green: 103/255, blue: 106/255, alpha: 1)<br>        separatorLabel.translatesAutoresizingMaskIntoConstraints = false<br>        container.addSubview(separatorLabel)<br>        // 貼文狀態<br>        let stateButton = UIButton()<br>        if postArray[selectSection].isPublic {<br>            stateButton.setImage(UIImage(systemName: &quot;globe.asia.australia.fill&quot;), for: .normal)<br>        } else {<br>            stateButton.setImage(UIImage(systemName: &quot;person.2.fill&quot;), for: .normal)<br>        }<br>        stateButton.tintColor = UIColor(red: 101/255, green: 103/255, blue: 106/255, alpha: 1)<br>        stateButton.translatesAutoresizingMaskIntoConstraints = false<br>        container.addSubview(stateButton)<br>        <br>        // 設定auto layout條件<br>        NSLayoutConstraint.activate([<br>            profilePictureImageView.widthAnchor.constraint(equalToConstant: 44),<br>            profilePictureImageView.heightAnchor.constraint(equalToConstant: 44),<br>            nameLabel.heightAnchor.constraint(equalToConstant: 22),<br>            timeLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor),<br>            timeLabel.leadingAnchor.constraint(equalTo: nameLabel.leadingAnchor),<br>            timeLabel.heightAnchor.constraint(equalToConstant: 22),<br>            separatorLabel.widthAnchor.constraint(equalToConstant: 17),<br>            separatorLabel.heightAnchor.constraint(equalToConstant: 22),<br>            stateButton.widthAnchor.constraint(equalToConstant: 22),<br>            stateButton.heightAnchor.constraint(equalToConstant: 22),<br>            <br>            nameLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor),<br>            nameLabel.topAnchor.constraint(equalTo: container.topAnchor),<br>            timeLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor),<br>            timeLabel.bottomAnchor.constraint(equalTo: container.bottomAnchor),<br>            separatorLabel.leadingAnchor.constraint(equalTo: timeLabel.trailingAnchor),<br>            separatorLabel.bottomAnchor.constraint(equalTo: container.bottomAnchor),<br>            stateButton.leadingAnchor.constraint(equalTo: separatorLabel.trailingAnchor),<br>            stateButton.bottomAnchor.constraint(equalTo: container.bottomAnchor)<br>        ])<br>        <br>        <br>        let userItem = UIBarButtonItem(customView: container)<br>        <br>        navigationItem.leftBarButtonItems = [backButtonItem, profilePictureItem, userItem]<br>    }<br><br>      // 返回上一頁按鈕的功能<br>    @objc func backButtonTapped () {<br>        navigationController?.popViewController(animated: true)<br>    }</pre><p><strong>留言按鈕樣式設定</strong></p><p>系統原有的圖示向上 旋轉調整成向右</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*p4Ay-qP4zJgSmLHIYlk6pA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2WbOjyjqjprMXfnK5Ry6qw.png" /></figure><pre>    func updateUI() {<br>        sendButton.transform = CGAffineTransform(rotationAngle: .pi/2)<br>        sendButton.tintColor = UIColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1)<br>    }</pre><p><strong>留言欄隨著鍵盤變動位置(通知功能)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*TaMIyqw2u_UxzIcns98GYg.gif" /><figcaption>鍵盤顯示或隱藏 留言欄變動位置</figcaption></figure><pre>    // ContainerView與留言欄auto layout條件<br>    @IBOutlet weak var postContainerViewBottomConstraint: NSLayoutConstraint!<br><br>    func registerForKeyboardNotifications() {<br>        // 鍵盤出現<br>        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)<br>        // 鍵盤隱藏<br>        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)<br>    }<br>    <br>    @objc func keyboardWasShown(_ notification: NSNotification) {<br>        guard let info = notification.userInfo,<br>              let keyboardFrameValue = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue,<br>              let tabHeight = tabBarController?.tabBar.frame.size.height else { return }<br>        let keyboardFrame = keyboardFrameValue.cgRectValue<br>        let keyboardSize = keyboardFrame.size<br>        self.commentView.transform = CGAffineTransform(translationX: 0, y: -(keyboardSize.height - tabHeight))<br>        // 變動ContainerView與留言欄auto layout條件<br>        postContainerViewBottomConstraint.constant = -(commentView.frame.height)<br>        <br>        // 留言欄移動的動畫設定<br>        UIView.animate(withDuration: 0.3) {<br>            self.view.layoutIfNeeded()<br>        }<br>        <br>    }<br>    <br>    <br>    @objc func keyboardWillBeHidden(_ notification: NSNotification) {<br>        // 重置ContainerView與留言欄auto layout條件<br>        postContainerViewBottomConstraint.constant = 0<br>        commentView.transform = CGAffineTransform(translationX: 0, y: 0)<br>    }</pre><p>留言功能</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*PriNuwQW6c5RF6YN9hmvMQ.gif" /><figcaption>留言欄位</figcaption></figure><pre>    @IBAction func commentChangeButtonColor(_ sender: Any) {<br>        <br>        if let text = commentTextField.text, !text.isEmpty {<br>            // 輸入文字發送按鈕變藍色<br>            sendButton.tintColor = UIColor(red: 23/255, green: 119/255, blue: 241/255, alpha: 1)<br>        } else {<br>            sendButton.tintColor = UIColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1)<br>        }<br>        <br>    }<br>   <br>    @IBAction func comment(_ sender: Any) {<br>        if let text = commentTextField.text, !text.isEmpty {<br>            let postComment = PostComment(userName: &quot;Lou&quot;, profilePictureName: &quot;userphoto&quot;, content: text, timestamp: Date()) // 留言功能<br>            postArray[selectSection].postComments.append(postComment)<br>            delegate?.updateTable() // 代理CommentTableViewController更新表格<br>            commentTextField.text = &quot;&quot; // 留言發送後 清除文字<br>            view.endEditing(true) // 留言發送後 收鍵盤<br>            sendButton.tintColor = UIColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1) // 發送鈕顏色變回預設<br>        }<br>    }<br>    <br>    // 點選其他地方 收鍵盤<br>    @IBAction func closeKeyboard(_ sender: Any) {<br>        view.endEditing(true)<br>    }</pre><blockquote>CommentTableViewController委託CommentViewController代理更新表單</blockquote><p>ViewController需要用到TableViewController的更新表單功能</p><p>且傳遞資料到TableViewController</p><pre>import UIKit<br><br>// 建立更新表格的協議<br>protocol CommentViewControllerDelegate: AnyObject {<br>    func updateTable()<br>}<br><br>class CommentViewController: UIViewController {<br>    weak var delegate: CommentViewControllerDelegate? // 代理人<br><br>    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>        if segue.identifier == &quot;embedCommentTableViewControllerSegue&quot;,<br>           let commentTableVC = segue.destination as? CommentTableViewController {<br>            // 傳遞資料<br>            commentTableVC.selectSection = selectSection<br>            // CommentTableViewController設定為代理人<br>            commentTableVC.delegate = self<br>            // CommentViewController設定為CommentTableViewController代理人<br>            self.delegate = commentTableVC<br>        }<br>    }<br>}<br><br>extension CommentViewController: CommentButtonDelegate {<br>    <br>    func commentButtonTapped() {<br>        commentTextField.becomeFirstResponder()<br>    }<br>}</pre><blockquote>CommentViewController委託CommentTableViewController代理鍵盤彈出</blockquote><p>TableViewController需要用到ViewController留言欄的鍵盤彈出功能</p><pre>import UIKit<br><br>protocol CommentButtonDelegate: AnyObject {<br>    func commentButtonTapped()<br>}<br><br>class CommentTableViewController: UITableViewController {<br>    <br>    weak var delegate: CommentButtonDelegate?<br><br>    @IBAction func commentButtonTapped(_ sender: UIButton) {<br>        delegate?.commentButtonTapped()<br>    }<br>}<br><br><br>extension CommentTableViewController: CommentViewControllerDelegate {<br>    <br>    func updateTable() {<br>        tableView.reloadData()<br>    }<br>}</pre><blockquote>CommentTableViewController</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPH1FaV7EmWLQAEHxvl3zg.png" /><figcaption>TableViewCell分佈</figcaption></figure><pre>override func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        guard let selectSection = selectSection else { return 3 }<br>        return 3 + postArray[selectSection].postComments.count // 留言數增加Section<br>    }<br>    <br>    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>            return 1<br>    }<br>    <br>    <br>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell: UITableViewCell<br>        guard let selectSection = selectSection else { return UITableViewCell() }<br>        <br>        if indexPath.section == 0 {<br>            guard let postCell = tableView.dequeueReusableCell(withIdentifier: &quot;\(PostTableViewCell.self)&quot;, for: indexPath) as? PostTableViewCell else { fatalError(&quot;PostTableViewCell failed&quot;) }<br>            let postInfo = postArray[selectSection]<br>            postCell.updateUI(with: postInfo)<br>            cell = postCell<br><br>        } else if indexPath.section == 1 {<br>            guard let postButtonCell = tableView.dequeueReusableCell(withIdentifier: &quot;\(PostButtonTableViewCell.self)&quot;, for: indexPath) as? PostButtonTableViewCell else { fatalError(&quot;PostBarTableViewCell failed&quot;) }<br>            let postInfo = postArray[selectSection]<br>            postButtonCell.updateUI(with: postInfo)<br>            cell = postButtonCell<br><br>        } else if indexPath.section == 2 {<br>            guard let likesCell = tableView.dequeueReusableCell(withIdentifier: &quot;\(LikesTableViewCell.self)&quot;, for: indexPath) as? LikesTableViewCell else { fatalError(&quot;LikesTableViewCell failed&quot;) }<br>            let postInfo = postArray[selectSection]<br>            likesCell.updateUI(with: postInfo)<br>            cell = likesCell<br><br>        } else {<br>            guard let commentCell = tableView.dequeueReusableCell(withIdentifier: &quot;\(CommentTableViewCell.self)&quot; , for: indexPath) as? CommentTableViewCell else { fatalError(&quot;CommentTableViewCell failed &quot;) }<br>            let postComment = postArray[selectSection].postComments[indexPath.section - 3]<br>            commentCell.updateUI(with: postComment)<br>            cell = commentCell<br><br>        }<br>        // 設定背景色為透明<br>        let backgroundView = UIView()<br>        backgroundView.backgroundColor = UIColor.clear<br><br>        // cell 的 selectedBackgroundView<br>        cell.selectedBackgroundView = backgroundView<br>        return cell<br>    }</pre><blockquote>四種自訂的TableViewCell</blockquote><p>PostTableViewCell (Section 0) 顯示貼文文字內容與圖片</p><pre>import UIKit<br><br>class PostTableViewCell: UITableViewCell {<br><br>    @IBOutlet weak var postMessageLabel: UILabel!<br>    @IBOutlet weak var postImageView: UIImageView!<br><br>    <br>    override func awakeFromNib() {<br>        super.awakeFromNib()<br>    }<br><br>    override func setSelected(_ selected: Bool, animated: Bool) {<br>        super.setSelected(selected, animated: animated)<br>    }<br>    <br>    func updateUI(with postInfo: PostInfo) {<br>        <br>        postMessageLabel.text = postInfo.text<br>        if let imageName = postInfo.imageName {<br>            if UUID(uuidString: imageName) != nil { // imageName是UUID，從文件系統讀取<br>                let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!<br>                let fileURL = documentsDirectory.appendingPathComponent(imageName)<br><br>                postImageView.image = UIImage(contentsOfFile: fileURL.path)<br>            } else { // 從Asset圖庫讀取<br>                postImageView.image = UIImage(named: imageName)<br>            }<br>        } else {<br>            postImageView.image = nil<br>        }<br>    }<br>}</pre><p>PostButtonTableViewCell (Section 1) 按讚 留言 分享功能欄</p><pre>import UIKit<br><br>class PostButtonTableViewCell: UITableViewCell {<br><br>    @IBOutlet weak var likeButton: UIButton!<br>    @IBOutlet weak var commentButton: UIButton!<br><br>    override func awakeFromNib() {<br>        super.awakeFromNib()<br>    }<br><br>    override func setSelected(_ selected: Bool, animated: Bool) {<br>        super.setSelected(selected, animated: animated)<br>    }<br>    <br>    func updateUI(with postInfo: PostInfo){<br>        if postInfo.isLiked {<br>            likeButton.setImage(UIImage(systemName: postInfo.likeButtonImageName), for: .normal)<br>            likeButton.tintColor = UIColor(red: 23/255, green: 119/255, blue: 241/255, alpha: 1)<br>        } else {<br>            likeButton.setImage(UIImage(systemName: postInfo.likeButtonImageName), for: .normal)<br>            likeButton.tintColor = UIColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1)<br>        }<br>    }<br>}</pre><p>LikesTableViewCell (Section 2) 按讚數量 分享數量</p><pre>import UIKit<br><br>class LikesTableViewCell: UITableViewCell {<br><br>    @IBOutlet weak var LikesLabel: UILabel!<br>    @IBOutlet weak var sharesLabel: UILabel!<br>    <br>    override func awakeFromNib() {<br>        super.awakeFromNib()<br>    }<br><br>    override func setSelected(_ selected: Bool, animated: Bool) {<br>        super.setSelected(selected, animated: animated)<br>    }<br>    <br>    func updateUI(with postInfo: PostInfo){ <br>        LikesLabel.text = String(postInfo.likes)<br>        sharesLabel.text = String(postInfo.shares)+&quot;次分享&quot;<br>    }<br><br>}</pre><p>CommentTableViewCell (Section 3) 留言內容</p><pre>import UIKit<br><br>class CommentTableViewCell: UITableViewCell {<br>    <br>    @IBOutlet weak var userImageView: UIImageView!<br>    @IBOutlet weak var commentLabel: UILabel!<br>    @IBOutlet weak var timeLabel: UILabel!<br>    @IBOutlet weak var likeButton: UIButton!<br>    @IBOutlet weak var likesLabel: UILabel!<br>    <br>    <br>    override func awakeFromNib() {<br>        super.awakeFromNib()<br>    }<br><br>    override func setSelected(_ selected: Bool, animated: Bool) {<br>        super.setSelected(selected, animated: animated)<br>    }<br>    <br>    func updateUI(with postComment: PostComment) {<br>        userImageView.image = UIImage(named: postComment.profilePictureName)<br>        commentLabel.text = &quot;\(postComment.userName)\n\(postComment.content)&quot;<br>        timeLabel.text = timeAgoDisplay(date: postComment.timestamp)<br>        if postComment.likes != 0 {<br>            likesLabel.text = &quot;\(postComment.likes)👍&quot;<br>        } else {<br>            likesLabel.text = &quot;&quot;<br>        }<br>        if postComment.isLiked {<br>            likeButton.tintColor = UIColor(red: 23/255, green: 119/255, blue: 241/255, alpha: 1)<br>        } else {<br>            likeButton.tintColor = UIColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1)<br>        }<br>    }<br>}</pre><p>貼文按讚功能</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*fygM8Z0Gxa8TwPbAmwX5TA.gif" /><figcaption>貼文like</figcaption></figure><pre> @IBAction func likePost(_ sender: UIButton) {<br>        <br>        guard let selectSection = selectSection else { return }<br>        <br>        postArray[selectSection].isLiked = !postArray[selectSection].isLiked<br>        let likeBtnImageName = postArray[selectSection].likeButtonImageName<br>        sender.setImage(UIImage(systemName: likeBtnImageName), for: .normal)<br>        <br>        if postArray[selectSection].isLiked {<br>            sender.tintColor = UIColor(red: 23/255, green: 119/255, blue: 241/255, alpha: 1)<br>        } else {<br>            sender.tintColor = UIColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1)<br>        }<br>        // 取得likecountLabel所在的 indexPath<br>        let postIndexPath = [IndexPath(row: 0, section: 2)]<br>        // 重新載入表格<br>        tableView.reloadRows(at: postIndexPath, with: .none)<br>    }</pre><p>留言按讚功能</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*teTDxjTIbA64p9uRkLLtYg.gif" /><figcaption>留言like</figcaption></figure><pre>    @IBAction func likeComment(_ sender: UIButton) {<br>        let point = sender.convert(CGPoint.zero, to: tableView)<br>        if let indexPath = tableView.indexPathForRow(at: point),<br>            let selectSection = selectSection {<br>            let section = indexPath.section<br>            let commentSection = section - 3<br>            postArray[selectSection].postComments[commentSection].isLiked = !postArray[selectSection].postComments[commentSection].isLiked<br>            <br>            if postArray[selectSection].postComments[commentSection].isLiked {<br>                sender.tintColor = UIColor(red: 23/255, green: 119/255, blue: 241/255, alpha: 1)<br>            } else {<br>                sender.tintColor = UIColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1)<br>            }<br>            <br>            let commentIndexPath = [IndexPath(row: 0, section: section)]<br>            tableView.reloadRows(at: commentIndexPath, with: .none)<br>        }<br> <br>    }</pre><p>下篇繼續介紹part4</p><ul><li><a href="https://medium.com/@hover1202/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part4-73ce6020809e">#22 實作 Table View 的基本功能 -FB 頁面 part4</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/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-f4e38483ec06">#22 實作 Table View 的基本功能 -FB 頁面 part1</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/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part2-12ac545edd1d">#22 實作 Table View 的基本功能 -FB 頁面 part2</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91c9b0057571" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part3-91c9b0057571">#22 實作 Table View 的基本功能 -FB 頁面 part3</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[#22 實作 Table View 的基本功能 -FB 頁面 part2]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part2-12ac545edd1d?source=rss-ecffe12b9c07------2</link>
            <guid isPermaLink="false">https://medium.com/p/12ac545edd1d</guid>
            <dc:creator><![CDATA[Lou]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 22:02:16 GMT</pubDate>
            <atom:updated>2023-07-27T16:24:02.717Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*xSgpvd8f2qRdVECBrUO8gA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67hjzG7jB-Q6RPwot2TlCw.png" /><figcaption>四個ViewController</figcaption></figure><blockquote>HomePageTableViewController</blockquote><p>排序貼文功能 viewWillAppear(在畫面出現之前)</p><pre><br>    override func viewWillAppear(_ animated: Bool) {<br>        super.viewWillAppear(animated)<br>        // 按照時間排序貼文<br>        postArray.sort { (post1, post2) -&gt; Bool in<br>            return post1.timestamp &gt; post2.timestamp<br>        }<br>        // 更新表格<br>        tableView.reloadData()<br>    }</pre><p>自訂Navigation bar (加入menu按鈕)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*x-V4zosLPNpRridScwAn2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*zfLu50Ys6wL9mZyr28vQbA.gif" /><figcaption>Navigation bar分別左右兩邊區塊(加入menu按鈕)</figcaption></figure><pre>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setNavigationbar()<br>    }<br><br>    func setNavigationbar() {<br>        // 設定左邊選單按鈕<br>        let menuButton = UIButton(type: .system)<br>        menuButton.frame = CGRect(x: 0, y: 0, width: 10, height: 40)<br>        let leftBarSymbolConfig = UIImage.SymbolConfiguration(weight: .heavy)<br>        let menuImage = UIImage(systemName: &quot;line.3.horizontal&quot;, withConfiguration: leftBarSymbolConfig)<br>        menuButton.setImage(menuImage, for: .normal)<br>        menuButton.tintColor = UIColor(red: 5/255, green: 5/255, blue: 5/255, alpha: 1)<br>        let barButtonItem = UIBarButtonItem(customView: menuButton)<br>        <br>        // 設定標題<br>        let label = UILabel()<br>        label.text = &quot;facebook&quot;<br>        label.textColor = UIColor(red: 23/255, green: 119/255, blue: 241/255, alpha: 1)<br>        label.font = UIFont.boldSystemFont(ofSize: 30)<br>        let labelItem = UIBarButtonItem(customView: label)<br>        <br>        // 設定rightBarButtonItems的symbol圖片統一的樣式<br>        let rightBarSymbolConfig = UIImage.SymbolConfiguration(weight: .heavy)<br>        // 設定messageButton樣式<br>        let messageButton = UIButton(type: .system)<br>        messageButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)<br>        let messageImage = UIImage(systemName: &quot;message.fill&quot;, withConfiguration: rightBarSymbolConfig)<br>        messageButton.setImage(messageImage, for: .normal)<br>        messageButton.backgroundColor = UIColor(red: 228/255, green: 229/255, blue: 234/255, alpha: 1)<br>        messageButton.tintColor = UIColor(red: 5/255, green: 5/255, blue: 5/255, alpha: 1)<br>        messageButton.layer.cornerRadius = 20<br>        let messageBarButtonItem = UIBarButtonItem(customView: messageButton)<br>        <br>        // 設定searchButton樣式<br>        let searchButton = UIButton(type: .system)<br>        searchButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)<br>        let searchImage = UIImage(systemName: &quot;magnifyingglass&quot;, withConfiguration: rightBarSymbolConfig)<br>        searchButton.setImage(searchImage, for: .normal)<br>        searchButton.backgroundColor = UIColor(red: 228/255, green: 229/255, blue: 234/255, alpha: 1)<br>        searchButton.tintColor = UIColor(red: 5/255, green: 5/255, blue: 5/255, alpha: 1)<br>        searchButton.layer.cornerRadius = 20<br>        let searchBarButtonItem = UIBarButtonItem(customView: searchButton)<br>        <br>        // 設定plusButton樣式<br>        let plusButton = UIButton(type: .system)<br>        plusButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)<br>        let plusImage = UIImage(systemName: &quot;plus&quot;, withConfiguration: rightBarSymbolConfig)<br>        plusButton.setImage(plusImage, for: .normal)<br>        plusButton.backgroundColor = UIColor(red: 228/255, green: 229/255, blue: 234/255, alpha: 1)<br>        plusButton.tintColor = UIColor(red: 5/255, green: 5/255, blue: 5/255, alpha: 1)<br>        plusButton.layer.cornerRadius = 20<br>        // 設定選單(menu)按鈕<br>        plusButton.showsMenuAsPrimaryAction = true<br>        plusButton.menu = UIMenu(children: [UIAction(title: &quot;發佈&quot;,image: UIImage(systemName: &quot;square.and.pencil&quot;) ,handler: { _ in<br>            self.performSegue(withIdentifier: &quot;showPostViewController&quot;, sender: self)<br>        }),<br>                                            UIAction(title: &quot;限時動態&quot;,image: UIImage(systemName: &quot;book.fill&quot;) ,handler: { _ in<br>            print(&quot;限時動態&quot;)<br>        }),<br>                                            UIAction(title: &quot;連續短片&quot;,image: UIImage(systemName: &quot;play.rectangle.fill&quot;) ,handler: { _ in<br>            print(&quot;連續短片&quot;)<br>        }),<br>                                            UIAction(title: &quot;直播&quot;,image: UIImage(systemName: &quot;video.fill&quot;) ,handler: { _ in<br>            print(&quot;直播&quot;)<br>        })<br>                                           ])<br>        let plusBarButtonItem = UIBarButtonItem(customView: plusButton)<br>        <br>        <br>        //加入按鈕樣式到Navugation<br>        navigationItem.leftBarButtonItems = [barButtonItem, labelItem]<br>        navigationItem.rightBarButtonItems = [messageBarButtonItem, searchBarButtonItem, plusBarButtonItem]<br>    }</pre><p>貼文按讚功能</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*L_J_48qB3bofXSypAPa-NQ.gif" /><figcaption>按讚</figcaption></figure><pre>    @IBAction func likePost(_ sender: UIButton) {<br>        <br>        let point = sender.convert(CGPoint.zero, to: tableView) // 點選button的位置<br>        if let indexPath = tableView.indexPathForRow(at: point){<br>            let section = indexPath.section<br>            let postSection = section - 2 // section第三個開始才是貼文<br>            postArray[postSection].isLiked = !postArray[postSection].isLiked // 按讚 收回讚<br>            let likeButtonImageName = postArray[postSection].likeButtonImageName<br>            sender.setImage(UIImage(systemName: likeButtonImageName), for: .normal)<br>            <br>            if postArray[postSection].isLiked {<br>                sender.tintColor = UIColor(red: 23/255, green: 119/255, blue: 241/255, alpha: 1)<br>            } else {<br>                sender.tintColor = UIColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1)<br>            }<br>            <br>            // 取得likecountLabel所在的 indexPath<br>            let postIndexPath = [IndexPath(row: 0, section: section)]<br>            // 重新載入表格<br>            tableView.reloadRows(at: postIndexPath, with: .none)<br>            <br>        }<br>    }</pre><p>點選貼文cell功能(傳遞資料)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*ygZ8w1CegOhgjeixV-eAew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*hhBVSh1P1_ZnkrLAMjZZgw.gif" /><figcaption>cell連結 SegueAction 查看內文</figcaption></figure><p>取得cell的section位置 傳遞到CommentViewController</p><pre>    @IBSegueAction func showPost(_ coder: NSCoder) -&gt; CommentViewController? {<br>        guard let section = tableView.indexPathForSelectedRow?.section else { return nil }<br>        let selectSection = section - 2<br>        return CommentViewController(coder: coder, selectSection: selectSection, shouldOpenKeyboard: false)<br>    }</pre><p>點選留言按鈕功能(傳遞資料)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*xEekE_ix6JbRtPt8sAaiXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*uuKwLxqt-cIjjlg0nE9tCw.gif" /><figcaption>點選留言按鈕 進入內文留言 彈出鍵盤</figcaption></figure><p>commentButton Action取得按鈕的Section位置</p><pre>    @IBAction func commentButtonTapped(_ sender: UIButton) {<br>        self.selectedSection = sender.tag<br>    }</pre><p>commentButton SegueAction傳遞資料到CommentViewController</p><pre>    @IBSegueAction func showPostComment(_ coder: NSCoder) -&gt; CommentViewController? {<br>        guard let section = self.selectedSection else { return nil }<br>            let selectSection = section - 2<br>        return CommentViewController(coder: coder, selectSection: selectSection, shouldOpenKeyboard: true)<br>    }</pre><p>照片點選功能</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*NlIhGqYTn4rxFfYKcvf2FQ.png" /><figcaption>選取照片按鈕</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*nqgkm2AoERk4xls58RQh3g.gif" /><figcaption>選取照片功能</figcaption></figure><pre>import PhotosUI<br><br>extension HomePageTableViewController: PHPickerViewControllerDelegate {<br>    <br>    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {<br>        picker.dismiss(animated: true)<br><br>        guard !results.isEmpty else {<br>            // 使用者沒有選擇照片<br>            return<br>        }<br><br>        let itemProvider = results.first?.itemProvider<br><br>        if let itemProvider = itemProvider, itemProvider.canLoadObject(ofClass: UIImage.self) {<br>            itemProvider.loadObject(ofClass: UIImage.self) { [weak self] (object, error) in<br>                DispatchQueue.main.async {<br>                    if let error = error {<br>                        print(&quot;Error loading image: \(error)&quot;)<br>                        return<br>                    }<br><br>                    if let image = object as? UIImage {<br>                        // 使用 Segue 跳轉 PostViewController傳遞圖片<br>                        self?.performSegue(withIdentifier: &quot;selcetPhoto&quot;, sender: image)<br>                    }<br>                }<br>            }<br>        }<br><br>    }<br>}</pre><p>傳遞選取照片資料到下一頁(func prepare()必須有Segue才會觸發)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ckhd1jPJTXljmMYeUk9nwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*l-C1NuPHauom5ARtXBm8SA.png" /><figcaption>設定segue identifier</figcaption></figure><pre>     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>         if segue.identifier == &quot;selcetPhoto&quot;,<br>            let postViewController = segue.destination as? PostViewController,<br>            let image = sender as? UIImage {<br>             postViewController.selectedImage = image<br>         }</pre><p>下篇介紹part3</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/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part3-91c9b0057571">#22 實作 Table View 的基本功能 -FB 頁面 part3</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%E5%95%8F%E9%A1%8C%E8%A7%A3%E7%AD%94%E9%9B%86/ios-14-%E6%8F%90%E4%BE%9B%E5%A4%9A%E9%81%B8%E7%85%A7%E7%89%87%E5%8A%9F%E8%83%BD%E7%9A%84-phpickerviewcontroller-d9733d203222">iOS 14 提供多選照片功能的 PHPickerViewController</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/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-f4e38483ec06">#22 實作 Table View 的基本功能 -FB 頁面 part1</a></li><li><a href="https://medium.com/@hover1202/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part4-73ce6020809e">#22 實作 Table View 的基本功能 -FB 頁面 part4</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12ac545edd1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part2-12ac545edd1d">#22 實作 Table View 的基本功能 -FB 頁面 part2</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[#22 實作 Table View 的基本功能 -FB 頁面 part1]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-f4e38483ec06?source=rss-ecffe12b9c07------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4e38483ec06</guid>
            <dc:creator><![CDATA[Lou]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 12:29:45 GMT</pubDate>
            <atom:updated>2023-07-27T16:25:20.791Z</atom:updated>
            <content:encoded><![CDATA[<p>有87分像的FB介面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*uZtCteh9OB0XX3jtzEt4iQ.png" /><figcaption>完美仿照</figcaption></figure><blockquote>貼文資料</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOnY1xZMPb-tEzRyufIisw.png" /><figcaption>手動編輯貼文內容</figcaption></figure><pre>struct PostInfo { // 貼文資訊<br>    let userName: String<br>    let profilePictureName: String<br>    let timestamp: Date<br>    let isPublic: Bool<br>    let text: String?<br>    let imageName: String?<br>    var likes: Int = 0<br>    var commentsCount: Int { // 計算屬性（Computed Properties）<br>        var count = postComments.count<br>        for postComment in postComments {<br>            count += postComment.replyComments.count<br>        }<br>        return count<br>    }<br>    var shares: Int = 0<br>    var isLiked: Bool = false { // 觀察屬性（Property Observers）<br>        didSet {<br>            if isLiked {<br>                likes += 1<br>            } else {<br>                likes -= 1<br>            }<br>        }<br>    }<br>    var likeButtonImageName:String { // 計算屬性（Computed Properties）<br>        get {<br>            isLiked ? &quot;hand.thumbsup.fill&quot; : &quot;hand.thumbsup&quot;<br>        }<br>        set {<br>            isLiked = newValue == &quot;hand.thumbsup.fill&quot; ? true : false<br>        }<br>    }<br>    var postComments: [PostComment] = []<br>}<br><br>struct PostComment { // 貼文留言<br>    let userName: String<br>    let profilePictureName: String<br>    let content: String<br>    let timestamp: Date<br>    var isLiked: Bool = false { // 觀察屬性（Property Observers）<br>        didSet {<br>            if isLiked {<br>                likes += 1<br>            } else {<br>                likes -= 1<br>            }<br>        }<br>    }<br>    var likes: Int = 0<br>    var replyComments: [ReplyComments] = []<br>}<br><br>struct ReplyComments { // 貼文留言中的回覆留言<br>    let userName: String<br>    let profilePictureName: String<br>    let content: String<br>    let timestamp: Date<br>    var isLiked: Bool = false { // 觀察屬性（Property Observers）<br>        didSet {<br>            if isLiked {<br>                likes += 1<br>            } else {<br>                likes -= 1<br>            }<br>        }<br>    }<br>    var likes: Int = 0<br>}</pre><blockquote>首頁HomePage Table View Controller 佈局</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ADI1qXYJjfFi0IRxc9EgGQ.png" /><figcaption>表格分區</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*J02s-HLZZw7JVxR-zjYOeg.png" /><figcaption>設定Content：Dynamic Prototypes、Prototype Cells：4</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*8GeCGhH2Zkrha65c_ruWiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*aBhbp0CmSZHM61mUmhMq1A.png" /><figcaption>四種自定義cell Table View Cell填入Identifier</figcaption></figure><pre>    override func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        return 2 + postArray.count //section 2 開始為貼文內容<br>    }<br>    <br>    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        return section &lt; 2 ? 1 : 2 //section 2 開始有兩個row<br>    }<br>    <br>    <br>    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell: UITableViewCell<br>        // 四種cell自訂樣式<br>        if indexPath.section == 0 {<br>            guard let topCell = tableView.dequeueReusableCell(withIdentifier: &quot;\(TopTableViewCell.self)&quot;, for: indexPath) as? TopTableViewCell else {<br>                fatalError(&quot;TopTableViewCell failed&quot;) }<br>            cell = topCell<br>            <br>        } else if indexPath.section == 1  {<br>            guard let storyCell = tableView.dequeueReusableCell(withIdentifier: &quot;\(StoryTableViewCell.self)&quot;, for: indexPath) as? StoryTableViewCell else { fatalError(&quot;StoryTableViewCell failed&quot;) }<br>            cell = storyCell<br>            <br>        } else if indexPath.row == 0 {<br>            guard let postCell = tableView.dequeueReusableCell(withIdentifier: &quot;\(HomePagePostTableViewCell.self)&quot;, for: indexPath) as? HomePagePostTableViewCell else { fatalError(&quot;HomePagePostTableViewCell failed&quot;) }<br>            let postInfo = postArray[indexPath.section - 2]<br>            postCell.updateUI(with: postInfo)<br>            cell = postCell<br>        } else {<br>            guard let postButtonCell = tableView.dequeueReusableCell(withIdentifier: &quot;\(PostButtonTableViewCell.self)&quot;, for: indexPath) as? PostButtonTableViewCell else { fatalError(&quot;PostBarTableViewCell failed&quot;) }<br>            let postInfo = postArray[indexPath.section - 2]<br>            postButtonCell.updateUI(with: postInfo)<br>            postButtonCell.commentButton.tag = indexPath.section<br>            cell = postButtonCell<br>        }<br>        <br>        // 設定背景色為透明<br>        let backgroundView = UIView()<br>        backgroundView.backgroundColor = UIColor.clear<br>        <br>        // cell 的 selectedBackgroundView<br>        cell.selectedBackgroundView = backgroundView<br>    <br>        return cell<br>    }<br><br></pre><blockquote>StoryTableViewCell (Section 1) 限時動態欄位</blockquote><p><strong>自訂Table View Cell</strong></p><p>不同Cell內的元件outlet要拉到自訂的class TableViewCell</p><p>(action才可以直接拉進HomePageTableViewController)</p><p>限時動態欄位Story Table View Cell+Collection View呈現</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gYCzcky2Os1c-V4nqzmklw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*DYCgG4d5b3kpTlk1mmgLLw.gif" /><figcaption>Table View+Collection View</figcaption></figure><p>遵從UICollectionViewDataSource, UICollectionViewDelegate</p><pre>import UIKit<br><br>extension HomePageTableViewController: UICollectionViewDataSource, UICollectionViewDelegate {<br>    <br>    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>        return postArray.count + 1<br>    }<br>    <br>    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {<br>        <br>        if indexPath.row == 0{<br>            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;\(MyStoryCollectionViewCell.self)&quot;, for: indexPath) as? MyStoryCollectionViewCell else { fatalError(&quot;MyStoryCollectionViewCell failed&quot;) }<br>            cell.updateUI()<br>            return cell<br>        } else {<br>            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: &quot;\(StoryCollectionViewCell.self)&quot;, for: indexPath) as? StoryCollectionViewCell else { fatalError(&quot;StoryCollectionViewCell failed&quot;) }<br>            let postInfo = postArray[indexPath.row - 1]<br>            cell.updateUI(with: postInfo)<br>            return cell<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KM-gyEU_2U21TzmmcDDmwQ.png" /><figcaption>自訂兩種Collection View Cell</figcaption></figure><p>MyStoryCollectionViewCell (Row 0) 限時動態新增欄位</p><pre>class MyStoryCollectionViewCell: UICollectionViewCell {<br><br>    @IBOutlet weak var plusButton: UIButton!<br>    <br>    func updateUI() {<br>        layer.cornerRadius = 10<br>        layer.borderWidth = 1<br>        layer.borderColor = CGColor(red: 222/255, green: 223/255, blue: 225/255, alpha: 1)<br>        plusButton.layer.cornerRadius = 15<br>        plusButton.layer.borderWidth = 2<br>        plusButton.layer.borderColor = CGColor(red: 1, green: 1, blue: 1, alpha: 1)<br>    }<br>}</pre><p>StoryCollectionViewCell (Row 1以後) 限時動態貼文</p><pre>class StoryCollectionViewCell: UICollectionViewCell {<br><br>    @IBOutlet weak var storyProfilePictureImageView: UIImageView!<br>    @IBOutlet weak var storyPictureImageView: UIImageView!<br>    @IBOutlet weak var storyNameLabel: UILabel!<br>    @IBOutlet weak var storyBorderIamgeView: UIImageView!<br>    <br>    func updateUI(with postInfo: PostInfo) {<br>        layer.cornerRadius = 10<br>        layer.borderWidth = 1<br>        layer.borderColor = CGColor(red: 222/255, green: 223/255, blue: 225/255, alpha: 1)<br>        storyProfilePictureImageView.layer.cornerRadius = 18<br>        storyBorderIamgeView.layer.cornerRadius = 22<br>        storyBorderIamgeView.layer.borderWidth = 2<br>        storyBorderIamgeView.layer.borderColor = CGColor(red: 26/255, green: 116/255, blue: 229/255, alpha: 1)<br>        <br>        storyNameLabel.text = postInfo.userName<br>        storyProfilePictureImageView.image = UIImage(named: postInfo.profilePictureName)<br>        <br>        if let imageName = postInfo.imageName {<br>            storyPictureImageView.image = UIImage(named: imageName)<br>        } else {<br>            storyPictureImageView.image = nil<br>        }<br>    }<br>}</pre><p>HomePagePost與PostButton這兩個TableViewCell有設定更新UI function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*CNl2NUhMhpXW881nsx7HfA.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*T_htj4-4cAmwPvv23pZDeQ.png" /><figcaption>HomePagePost與PostButton有自訂更新UI function</figcaption></figure><blockquote>HomePagePostTableViewCell (Section 2) 貼文內容</blockquote><pre>class HomePagePostTableViewCell: UITableViewCell {<br>    <br>    @IBOutlet weak var profilePictureImageView: UIImageView!<br>    @IBOutlet weak var nameLabel: UILabel!<br>    @IBOutlet weak var timeLabel: UILabel!<br>    @IBOutlet weak var stateButton: UIButton!<br>    @IBOutlet weak var messageLabel: UILabel!<br>    @IBOutlet weak var postImageView: UIImageView!<br>    @IBOutlet weak var likeCountLabel: UILabel!<br>    @IBOutlet weak var messageShareLabel: UILabel!<br>    <br>    override func awakeFromNib() {<br>        super.awakeFromNib()<br>    }<br>    <br>    override func setSelected(_ selected: Bool, animated: Bool) {<br>        super.setSelected(selected, animated: animated)<br>    }<br>    <br>    func updateUI(with postInfo: PostInfo) {<br>        <br>        profilePictureImageView.image = UIImage(named: postInfo.profilePictureName)<br>        nameLabel.text = postInfo.userName<br>        timeLabel.text = timeAgoDisplay(date: postInfo.timestamp)<br>        if postInfo.isPublic {<br>            stateButton.setImage(UIImage(systemName: &quot;globe.asia.australia.fill&quot;), for: .normal)<br>        } else {<br>            stateButton.setImage(UIImage(systemName: &quot;person.2.fill&quot;), for: .normal)<br>        }<br>        messageLabel.text = postInfo.text<br>        if let imageName = postInfo.imageName {<br>            if UUID(uuidString: imageName) != nil { // imageName是UUID的話 從資料夾讀取<br>                let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!<br>                let fileURL = documentsDirectory.appendingPathComponent(imageName)<br><br>                postImageView.image = UIImage(contentsOfFile: fileURL.path)<br>            } else { // 從Asset圖庫讀取<br>                postImageView.image = UIImage(named: imageName)<br>            }<br>        } else {<br>            postImageView.image = nil<br>        }<br><br>        likeCountLabel.text = String(postInfo.likes)<br>        messageShareLabel.text = String(postInfo.commentsCount)+&quot;則留言 &quot;+String(postInfo.shares)+&quot;次分享&quot;<br>    }<br>}</pre><blockquote>PostButtonTableViewCell (Section 3) 按讚 留言 分享功能欄</blockquote><pre>class PostButtonTableViewCell: UITableViewCell {<br><br>    @IBOutlet weak var likeButton: UIButton!<br>    @IBOutlet weak var commentButton: UIButton!<br><br>    override func awakeFromNib() {<br>        super.awakeFromNib()<br>    }<br><br>    override func setSelected(_ selected: Bool, animated: Bool) {<br>        super.setSelected(selected, animated: animated)<br>    }<br>    <br>    func updateUI(with postInfo: PostInfo){<br>        if postInfo.isLiked {<br>            likeButton.setImage(UIImage(systemName: postInfo.likeButtonImageName), for: .normal)<br>            likeButton.tintColor = UIColor(red: 23/255, green: 119/255, blue: 241/255, alpha: 1)<br>        } else {<br>            likeButton.setImage(UIImage(systemName: postInfo.likeButtonImageName), for: .normal)<br>            likeButton.tintColor = UIColor(red: 100/255, green: 103/255, blue: 106/255, alpha: 1)<br>        }<br>    }<br>}</pre><blockquote>設定表格高度</blockquote><p>除了StoryTableViewCell以外的三個cell 都是用auto layout計算高度</p><pre>    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -&gt; CGFloat {<br>        return indexPath.section == 1 ? 180 : UITableView.automaticDimension<br>    }</pre><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/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part2-12ac545edd1d">#22 實作 Table View 的基本功能 -FB 頁面 part2</a></li><li><a href="https://medium.com/@hover1202/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part3-91c9b0057571">#22 實作 Table View 的基本功能 -FB 頁面 part3</a></li><li><a href="https://medium.com/@hover1202/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-part4-73ce6020809e">#22 實作 Table View 的基本功能 -FB 頁面 part4</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/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></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4e38483ec06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/22-%E5%AF%A6%E4%BD%9C-table-view-%E7%9A%84%E5%9F%BA%E6%9C%AC%E5%8A%9F%E8%83%BD-fb-%E9%A0%81%E9%9D%A2-f4e38483ec06">#22 實作 Table View 的基本功能 -FB 頁面 part1</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[#21 線上遊戲職業測驗App]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/21-%E7%B7%9A%E4%B8%8A%E9%81%8A%E6%88%B2%E8%81%B7%E6%A5%AD%E6%B8%AC%E9%A9%97app-4855a623cda3?source=rss-ecffe12b9c07------2</link>
            <guid isPermaLink="false">https://medium.com/p/4855a623cda3</guid>
            <dc:creator><![CDATA[Lou]]></dc:creator>
            <pubDate>Mon, 22 May 2023 12:06:44 GMT</pubDate>
            <atom:updated>2023-05-23T14:17:47.414Z</atom:updated>
            <content:encoded><![CDATA[<p>以魔力寶貝這款Q版2D角色扮演類線上遊戲職業作為設計題目，遊戲內擁有多樣化職業，替選擇困難的玩家設計職業測驗app。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*sVsIw-jJPd5dVtoH6CzQVw.gif" /><figcaption>操作畫面</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0hxuuEGIXBTVuvtwqH5CQ.png" /><figcaption>畫面設計</figcaption></figure><h4>建立Career檔案</h4><p>將所有職業建立enum （設定為字串,方便之後使用）</p><pre>enum CareerType: String {<br>    case 劍士, 戰斧鬥士, 騎士, 弓箭手, 格鬥士 // 戰鬥系<br>    case 魔術師, 傳教士, 巫師, 咒術師  // 法術系<br>    case 士兵, 忍者,舞者, 盜賊,爆彈師  // 準戰鬥系<br>    case 醫生, 護士 // 準戰鬥服務系<br>    case 封印師, 馴獸師, 飼養師 // 寵物系<br>    case 紡織工, 獵人, 樵夫, 礦工 // 採集系<br>    case 武器修理師, 防具修理師, 鑑定師, 偵探, 仙人 // 服務系<br>    case 武器製造師, 防具製造師, 寵裝製造師, 藥劑師, 廚師 // 製造系<br>}</pre><p>careerList職業清單字典 測驗結果key對照value顯示職業資訊</p><pre>struct CareerInfo {<br>    let career: CareerType<br>    let introduction: String<br>}<br><br>let careerList: [CareerType : CareerInfo]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PfdUEP9YPv3hcZrnEfPqA.png" /><figcaption>職業清單包含簡介資訊</figcaption></figure><p>scoreList分數清單 提供測驗計分</p><pre>struct CareerScore {<br>    let careerType: CareerType<br>    // 初始分數都為０<br>    var Score = 0<br>}<br><br>var scoreList: [CareerScore]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*v7NdKhtc1RY_zTpow6KTPg.png" /></figure><h4>建立Quiz檔案</h4><p>quizList測驗清單 放入測驗題目、選項、加分職業，利用enum CareerType很方便將職業類別加入也不用怕打錯字</p><pre>struct Option {<br>    let index: Int<br>    let text: String<br>    let careerTypes: [CareerType]<br>}<br><br>struct Question {<br>    let text: String<br>    let options: [Option]<br>}<br><br>var quizList = [Question]<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9mme1U5oPyObdfSQmkQHQ.png" /><figcaption>測驗題目及選項</figcaption></figure><blockquote>HomePageViewController</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*r7VktHBlCQefPGqiU2yCSQ.png" /><figcaption>登入測驗頁面</figcaption></figure><p>最簡單的功能 按鈕進入下一頁的測驗頁面，重新測驗時Function resetScores 將職業計分歸零</p><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        resetScores()<br><br>    }<br>    <br>    // 職業計分歸零<br>    func resetScores() {<br>        for index in 0..&lt;scoreList.count {<br>            scoreList[index].Score = 0<br>        }<br>    }</pre><blockquote>QuizViewController</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*plesmk8F3coxuAT4HekNAw.png" /><figcaption>測驗題目畫面</figcaption></figure><pre>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // 設定進度條動畫圖片<br>        progressGifPlayer()<br>        // 測驗題目順序隨機<br>        quizList.shuffle()<br>        // 載入測驗題目<br>        loadQuiz(questionNum: currentQuizIndex)<br>    }</pre><p><strong>進度條圖片gif動畫功能</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*MmdUHbW1bdPfhKX2qdM9pg.gif" /><figcaption>可愛鼠王 努力向前走</figcaption></figure><pre>func progressGifPlayer() {<br>        // 設定進度條動畫圖片的位置和大小<br>        progressImageView.frame.size.width = questionLabel.bounds.width * 0.25<br>        progressImageView.frame.size.height =<br>        questionLabel.bounds.height * 0.38<br>        progressImageView.center.y = answerProgressView.center.y<br>        progressImageView.frame.origin.x = answerProgressView.frame.origin.x - 20<br>        <br>        // 取得動畫圖片的資料<br>        guard let data = NSDataAsset(name: &quot;鼠王&quot;)?.data else { return }<br>        guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil) else { return }<br>        <br>        // 得到動畫幀數<br>        let frameCount = CGImageSourceGetCount(imageSource)<br>        var animationImages: [UIImage] = []<br>        <br>        // 將每個幀轉換成UIImage，並加入動畫圖片陣列<br>        for index in 0..&lt;frameCount {<br>            guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else { continue }<br>            let uiImage = UIImage(cgImage: cgImage)<br>            animationImages.append(uiImage)<br>        }<br>        <br>        // 設定進度條動畫的相關屬性<br>        self.progressImageView.animationImages = animationImages<br>        self.progressImageView.animationDuration = Double(frameCount) * 0.1 // 播放速度<br>        self.progressImageView.animationRepeatCount = 0 // 重複播放動畫<br>        self.progressImageView.startAnimating()<br>        <br>    }</pre><h4>載入題目功能</h4><pre>func loadQuiz(questionNum: Int) {<br>        // 設定題目<br>        let question = quizList[questionNum]<br>        questionLabel.text = question.text<br>        <br>        // 設置隨機選項<br>        var options = question.options<br>        options.shuffle()<br>        // 選項文字設定到按鈕上<br>        for i in 0..&lt;options.count {<br>            optionButton[i].setTitle(options[i].text, for: .normal)<br>            optionButton[i].tag = options[i].index<br>        }<br>        // 更新進度條和動畫圖片位置<br>        currentQuizIndex += 1<br>        answerProgressView.progress = Float(currentQuizIndex) / Float(quizList.count)<br>        progressImageView.frame.origin.x += answerProgressView.bounds.width/20<br>        <br>    }</pre><p><strong>答題計分功能</strong></p><p>利用UIButton.tag 得到選擇的選項按鈕，對應選項加分的職業，直到測驗完成，統計最高分的職業到結果頁面。（多個同分職業則隨機取出）</p><p><strong>用max(by:)</strong> 函式在 <strong>scoreList</strong> 中 找到<strong>Score</strong> 值最大的 <strong>CareerScore</strong> 物件，使用closure 接收兩個 <strong>CareerScore</strong> 物件<strong>{ $0.Score &lt; $1.Score }</strong> 根據 <strong>Score</strong> 屬性的值來進行比較。</p><pre>@IBAction func selectOption(_ sender: UIButton) {<br>        <br>        // 取得按鈕tag 對應選項index<br>        let index = sender.tag<br>        // 取得問題的選項清單<br>        let optionList = quizList[currentQuizIndex-1].options<br>        // 取得選項內對應的職業清單<br>        let optionScoreCareerList = optionList[index].careerTypes<br>        // 對應到的職業用迴圈加分<br>        for career in optionScoreCareerList {<br>            if let careerIndex = scoreList.firstIndex(where: { $0.careerType == career } ) {<br>                scoreList[careerIndex].Score += 1<br>            }<br>        }<br>        // 測驗題目完成<br>        if currentQuizIndex == quizList.count {<br>            // 找出最高分數<br>            let maxScore = scoreList.max(by: { $0.Score &lt; $1.Score })?.Score<br>            // 找出分數相同的職業<br>            let maxScoreCareers = scoreList.filter { $0.Score == maxScore }.map { $0.careerType }<br>            // 隨機選擇一個職業<br>            careerMatch = maxScoreCareers.randomElement()<br>            // showResultView<br>            performSegue(withIdentifier: &quot;showResultView&quot;, sender: sender)<br>            <br>            <br>        }else {<br>            // 題目還有 繼續測驗<br>            loadQuiz(questionNum: currentQuizIndex)<br>        }<br>    }</pre><h4>返回功能</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*VWiuRB09fzWKBj1zEnxi1A.gif" /><figcaption>回到上一題</figcaption></figure><p>firstIndex(where:) 是一個陣列方法，這個方法接收closure作為參數，在closure中，我們使用 $0 來表示陣列中的每個元素，並檢查 careerType 是否與 career 相等。如果相等 firstIndex(where:) 方法會回傳這個元素在陣列中的索引值。</p><p>找到在 scoreList 中的索引值後，我們使用 scoreList[careerIndex].Score -= 1 來將該職業的分數減1，恢復前一題測驗未加分的狀態。</p><pre>@IBAction func backButtonPressed(_ sender: UIButton) {<br>        // 避免第一題操作 超出陣列範圍<br>        if currentQuizIndex &gt; 1 {<br>            //載入題目時Index已經先+1 所以這邊要-2才會是上一題<br>            currentQuizIndex -= 2<br>            <br>            // 取得上一個選擇的選項index<br>            if let optionIndex = selectedOptionArray.last {<br>                let optionList = quizList[currentQuizIndex].options<br>                let optionScoreCareerList = optionList[optionIndex].careerTypes<br>                <br>                // 對應到的職業用迴圈減分<br>                for career in optionScoreCareerList {<br>                    if let careerIndex = scoreList.firstIndex(where: { $0.careerType == career } ) {<br>                        scoreList[careerIndex].Score -= 1<br>                    }<br>                }<br>               <br>            }<br>            <br>            // 移除最後一個選擇的選項index<br>            selectedOptionArray.removeLast()<br>            // 重新載入上一題的問題<br>            loadQuiz(questionNum: currentQuizIndex)<br>            // 更新進度條動畫圖片位置<br>            progressImageView.frame.origin.x -= answerProgressView.bounds.width/20*2<br>        }<br>        <br>    }</pre><p>利用print檢查返回上一題功能的分數是否正常</p><pre>// 印出每個職業的分數 檢查分數<br> for career in scoreList {<br>     print(&quot;\(career.careerType):\(career.Score)分&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*xiFCh2FUdyxEWTAw62E-ZQ.png" /><figcaption>測驗選項加分</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*c-1ZbAJcPJ-NB5w1NIyb0Q.png" /><figcaption>返回後扣分恢復</figcaption></figure><h4>傳遞資料功能</h4><p>傳遞測驗結果的職業到ResultViewController</p><pre>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {<br>        <br>        let controller = segue.destination as? ResultViewController<br>        <br>        if let careerMatch = careerMatch {<br>            controller?.careerMatch = careerMatch<br>        }<br>        <br>    }</pre><blockquote>ResultViewController</blockquote><p>測驗結果展示</p><p>接收測驗結果的職業類別對照careerList字典，利用.rawValue取得enum的資料類型，得到字串設定圖片和職業簡介。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*xKsXXF7D2tdi9KZIJZojZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*X2wQTDjUooOzQorFQsFEfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*c6t9ij6i7CiMdJJPnTT3Zw.png" /><figcaption>測驗結果 職業簡介</figcaption></figure><pre>  // 測驗結果的值<br>  var careerMatch: CareerType!<br><br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // 設定職業名稱標題<br>        careerNameLabel.text = careerList[careerMatch]?.career.rawValue<br>        // 設定職業圖片<br>        careerImage.image = UIImage(named: careerList[careerMatch]!.career.rawValue)<br>        // 設定職業介紹<br>        introductionLabel.text = careerList[careerMatch]?.introduction<br>        <br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*NVzktW5mzPQUjgf58MaKmw.gif" /><figcaption>重新測驗</figcaption></figure><p><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/16-%E5%BF%83%E7%90%86%E6%B8%AC%E9%A9%97%E6%88%96%E5%95%8F%E5%8D%B7-app-d8910d1345e">#16 心理測驗或問卷 App</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4855a623cda3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/21-%E7%B7%9A%E4%B8%8A%E9%81%8A%E6%88%B2%E8%81%B7%E6%A5%AD%E6%B8%AC%E9%A9%97app-4855a623cda3">#21 線上遊戲職業測驗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[#20 換算 App 加油費&回饋金計算機]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/20-%E6%8F%9B%E7%AE%97-app-%E5%8A%A0%E6%B2%B9%E8%B2%BB-%E5%9B%9E%E9%A5%8B%E9%87%91%E8%A8%88%E7%AE%97%E6%A9%9F-d61aa8e9dbf6?source=rss-ecffe12b9c07------2</link>
            <guid isPermaLink="false">https://medium.com/p/d61aa8e9dbf6</guid>
            <dc:creator><![CDATA[Lou]]></dc:creator>
            <pubDate>Tue, 09 May 2023 07:16:55 GMT</pubDate>
            <atom:updated>2024-08-16T13:16:57.964Z</atom:updated>
            <content:encoded><![CDATA[<p>速邁樂加油回饋金計算機</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*yhAfGAP6c9DXw175w4jpXw.gif" /></figure><blockquote>抓取中油油價公告牌價 使用XML解析</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*Cs9GxSYuibiJZ3LFehlTVQ.png" /><figcaption>中油公告牌價</figcaption></figure><p><a href="https://vipmbr.cpc.com.tw/CPCSTN/ListPriceWebService.asmx/getCPCMainProdListPrice_XML">https://vipmbr.cpc.com.tw/CPCSTN/ListPriceWebService.asmx/getCPCMainProdListPrice_XML</a></p><blockquote>建立CPCapiParserDelegate檔案 篩選所需要的資料</blockquote><pre>import Foundation<br><br>class CPCapiParserDelegate: NSObject, XMLParserDelegate{<br>    var currentItem: GasInfo?<br>    var currentElementValue: String?<br>    var resultArray = [GasInfo]()<br>    <br>    //  碰到標籤tag&lt;&gt;就會觸發 開始解析<br>    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {<br>        if elementName == &quot;Table&quot;{<br>            currentItem = GasInfo()<br>        }else if elementName == &quot;產品名稱&quot;{<br>            currentElementValue = nil<br>        }else if elementName == &quot;參考牌價&quot;{<br>            currentElementValue = nil<br>        }else if elementName == &quot;牌價生效時間&quot;{<br>            currentElementValue = nil<br>        }<br>    }<br>    <br>    //  再次 碰到相同標籤tag&lt;&gt;就會觸發 結束這段解析<br>    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {<br>        if elementName == &quot;Table&quot;{<br>            if currentItem != nil{<br>                resultArray.append(currentItem!)<br>                currentItem = nil<br>            }<br>        }else if elementName == &quot;產品名稱&quot;{<br>            currentItem?.name = currentElementValue<br>        }else if elementName == &quot;參考牌價&quot;{<br>            currentItem?.price = currentElementValue<br>        }else if elementName == &quot;牌價生效時間&quot;{<br>            currentItem?.effectiveDate = currentElementValue<br>        }<br>        currentElementValue = nil<br>    }<br>    <br>    // 碰到標籤的內文字母時 就會開時讀取<br>    <br>    func parser(_ parser: XMLParser, foundCharacters string: String) {<br>        if currentElementValue == nil{<br>            currentElementValue = string<br>        }else{<br>            currentElementValue = currentElementValue! + string<br>        }<br>    }<br>    <br>    func getResult() -&gt; [GasInfo]{<br>        return resultArray<br>    }<br>}</pre><blockquote>ViewController建立下載XML資料function</blockquote><pre>struct GasInfo {<br>    var name: String?<br>    var price: String?<br>    var effectiveDate: String?<br>}<br><br>class ViewController: UIViewController {<br> var downloadGasInfo = [GasInfo]()<br> var gasInfo = [GasInfo]()<br> let xmlAddress = &quot;https://vipmbr.cpc.com.tw/CPCSTN/ListPriceWebService.asmx/getCPCMainProdListPrice_XML&quot;<br><br>func downloadXML(withXMLAddress xmlAddress: String) {<br>        if let url = URL(string: xmlAddress){<br>            URLSession.shared.dataTask(with: url) { [self] (data, Response, error) in<br>                if error != nil {<br>                    let errorCode = (error! as NSError).code<br>                    if errorCode == -1009 {<br>                        DispatchQueue.main.async {<br>                            self.showAlert(title: &quot;目前沒有網路&quot;)<br>                        }<br>                    } else {<br>                        DispatchQueue.main.async {<br>                            self.showAlert(title: &quot;發生錯誤&quot;)<br>                        }<br>                    }<br>                    return<br>                }<br>                if let loadData = data {<br>                    let parser = XMLParser(data: loadData)<br>                    let cpcapiParserDelegate = CPCapiParserDelegate()<br>                    parser.delegate = cpcapiParserDelegate<br>                    if parser.parse() == true{<br>                        self.downloadGasInfo = cpcapiParserDelegate.getResult()<br>                        DispatchQueue.main.async {<br>                          //下載資料成功 更新UI<br>                            self.updateUI()<br>                        }<br>                    } else {<br>                        DispatchQueue.main.async {<br>                            self.showAlert(title: &quot;XML解析失敗&quot;)<br>                        }<br>                    }<br>                }<br>            }.resume()<br>        }<br>        <br>    }<br><br><br>    func showAlert(title: String) {<br>        let alert = UIAlertController(title: title, message: &quot;請稍後再試！&quot;, preferredStyle: .alert)<br>        alert.addAction(UIAlertAction(title: &quot;Ok&quot;, style: .default, handler: nil))<br>        present(alert, animated: true, completion: nil)<br>    }<br>}</pre><blockquote>設定UI</blockquote><pre>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        downloadXML(withXMLAddress: xmlAddress)<br>        getweekday()<br>    }<br><br>  func updateUI() {<br>        gasInfo = downloadGasInfo.filter{$0.name!.contains(&quot;92&quot;)} + downloadGasInfo.filter{$0.name!.contains(&quot;95&quot;)} + downloadGasInfo.filter{$0.name!.contains(&quot;98&quot;)} + downloadGasInfo.filter{$0.name!.contains(&quot;超級柴油&quot;)}<br>        <br>        for index in 0..&lt;gasInfo.count {<br>            gasItemSegmentedControl.setTitle(gasInfo[index].name, forSegmentAt: index)<br>        }<br>        gasPriceLabel.text = gasInfo[1].price<br>        gasName = gasInfo[1].name!<br>        gasPrice = Double(gasInfo[1].price!) ?? 0<br>        calculatefillupButton.setTitle(gasName + &quot; 加滿&quot;, for: .normal)<br>        calculateButton.setTitle(&quot;自訂加油金額&quot;, for: .normal)<br>        fuelMeterMaxTextField.text = String(fuelMeterMaxTextValue)<br>        fuelMeterMinTextField.text = String(fuelMeterMinTextValue)<br>    }<br>    </pre><blockquote>DatePicker顯示星期幾</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*7MckrMcvkid_GpOP5L3R2Q.gif" /><figcaption>DatePicker選擇日期 顯示星期</figcaption></figure><pre>   @IBAction func datePicker(_ sender: Any) {<br>        getweekday()<br>    }<br><br>func getweekday() {<br>        let dateComponemts = Calendar.current.dateComponents(in: TimeZone.current, from: datePicker.date)<br>        weekday = dateComponemts.weekday!<br>        var week = &quot;&quot;<br>        switch weekday {<br>            case 1:<br>                week = &quot;星期日&quot;<br>            case 2:<br>                week = &quot;星期一&quot;<br>            case 3:<br>                week = &quot;星期二&quot;<br>            case 4:<br>                week = &quot;星期三&quot;<br>            case 5:<br>                week = &quot;星期四&quot;<br>            case 6:<br>                week = &quot;星期五&quot;<br>            case 7:<br>                week = &quot;星期六&quot;<br>            default:<br>                break<br>        }<br>        dayLabel.text = &quot;加油日期(\(week)) :&quot;<br>    }</pre><blockquote>設定油箱、油表資料 顯示計算結果</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*cez3tF6MVu5zc0vV6lvYvQ.gif" /><figcaption>計算加油金額、公升數</figcaption></figure><p>油品SegmentedControl、油箱TextField、油表TextField、油表Stepper 連結同一個IBAction<br>資料變動顯示計算結果到加油金額TextField 、加油公升數Label</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*tT5LZWcakjgc3ULUSuk7pg.png" /><figcaption>連結同一個IBAction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*JxzQ5IfswluGdGEBU5hQGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*2EN3c3L3mjiGNQFJUdoYNg.png" /><figcaption>TextField 用Editing Changed連結IBAction 內容變更才會更新計算結果</figcaption></figure><pre>    @IBAction func fuelMeterCalculateFuelLiter(_ sender: Any) {<br>        //SegmentedControl選擇油品 價格更新<br>        switch gasItemSegmentedControl.selectedSegmentIndex {<br>        case 0:<br>            gasPriceLabel.text = gasInfo[0].price<br>            gasName = gasInfo[0].name!<br>            gasPrice = Double(gasInfo[0].price!) ?? 0<br>            calculatefillupButton.setTitle(gasName + &quot; 加滿&quot;, for: .normal)<br>        case 1:<br>            gasPriceLabel.text = gasInfo[1].price<br>            gasName = gasInfo[1].name!<br>            gasPrice = Double(gasInfo[1].price!) ?? 0<br>            calculatefillupButton.setTitle(gasName + &quot; 加滿&quot;, for: .normal)<br>        case 2:<br>            gasPriceLabel.text = gasInfo[2].price<br>            gasName = gasInfo[2].name!<br>            gasPrice = Double(gasInfo[2].price!) ?? 0<br>            calculatefillupButton.setTitle(gasName + &quot; 加滿&quot;, for: .normal)<br>        case 3:<br>            gasPriceLabel.text = gasInfo[3].price<br>            gasName = gasInfo[3].name!<br>            gasPrice = Double(gasInfo[3].price!) ?? 0<br>            calculatefillupButton.setTitle(gasName + &quot; 加滿&quot;, for: .normal)<br>        default:<br>            break<br>        }<br>        <br>        //設定油表變數&amp;顯示值<br>        fuelMeterMaxTextValue = Int(fuelMeterMaxStepper.value)<br>        fuelMeterMaxTextField.text = String(fuelMeterMaxTextValue)<br>        fuelMeterMinTextValue = Int(fuelMeterMinStepper.value)<br>        fuelMeterMinTextField.text = String(fuelMeterMinTextValue)<br>        <br>        //設定油箱&amp;油表 計算顯示加油金額&amp;加油公升數<br>        if let carFuelTank = Double(carFuelTankTextField.text!),<br>           let fuelMeterMax = Double(fuelMeterMaxTextField.text!),<br>           let fuelMeterMin = Double(fuelMeterMinTextField.text!),<br>            carFuelTank &gt; 0, fuelMeterMax &gt; 0, fuelMeterMin &gt; 0  {<br>            fuelLiter = carFuelTank / fuelMeterMax * (fuelMeterMax - fuelMeterMin)<br>            fuelCost = fuelLiter * gasPrice<br>            fuelLiterLabel.text = String(format: &quot;%.2f&quot;, fuelLiter)<br>            costTextField.text = String(format: &quot;%.f&quot;, fuelCost)<br>        }<br>    }</pre><blockquote>設定加油金額 顯示計算結果</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*RJJ8hfE0NF6kWanBiXC6Ew.gif" /><figcaption>計算加油公升數</figcaption></figure><pre>    @IBAction func fuelCostCalculateFuelLiter(_ sender: Any) {<br>        <br>        if let fuelCost = Double(costTextField.text!),<br>           let gasPrice = Double(gasPriceLabel.text!),<br>            fuelCost &gt; 0 {<br>            fuelLiter = fuelCost / gasPrice<br>            fuelLiterLabel.text = String(format: &quot;%.2f&quot;, fuelLiter)<br>            <br>        }<br>    }</pre><blockquote>建立計算加油回饋金function</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7V7gpNRtzpXg-ZSuUCA6JA.jpeg" /><figcaption>各種信用卡、加油日條件</figcaption></figure><pre>func calculateRebate (cost: Int) -&gt; Double {<br><br>        //設定加油回饋條件星期、卡別<br>        switch weekday {<br>            case 1:<br>                openpointRebate = 0.07<br>                if megaIcashPaySwitch.isOn, cost &gt;= 888 {<br>                    openpointRebate = openpointRebate + 0.05<br>                    payMessage = &quot;支付方式:兆豐 統一7-11獅聯名卡\n綁定icash Pay支付\n&quot;<br>                } else {<br>                    payMessage = &quot;支付方式: icash Pay支付 \n&quot;<br>                }<br>            case 3:<br>                openpointRebate = 0.07<br>                <br>                if fubonIcashPaySwitch.isOn, cost &gt;= 888 {<br>                    openpointRebate += 0.05<br>                    cashRebate = 0.055<br>                    payMessage = &quot;支付方式: 富邦 Open Possible聯名卡\n綁定icash Pay支付\n&quot;<br>                } else if fubonIcashPaySwitch.isOn {<br>                    cashRebate = 0.055<br>                    payMessage = &quot;支付方式: 富邦 Open Possible聯名卡\n綁定icash Pay支付\n&quot;<br>                } else {<br>                    payMessage = &quot;支付方式: icash Pay支付\n&quot;<br>                }<br>            case 7:<br>                if fuelLiter &gt;= 25 {<br>                    openpointRebate = 0.066<br>                    if cathayCubeSwitch.isOn {<br>                        openpointRebate += 0.07<br>                        treepointRebate = 0.03<br>                        payMessage = &quot;支付方式: 國泰世華 CUBE卡\n綁定OPNE錢包+集精選&quot;<br>                    } else if cathayFormosaSwitch.isOn {<br>                        openpointRebate += 0.033<br>                        payMessage = &quot;支付方式: 國泰世華 台塑聯名卡\n&quot;<br>                    }<br>                } else {<br>                    openpointRebate = 0.033<br>                }<br>            default:<br>                break<br>            }<br>        <br>        openpointback = Double(cost) * openpointRebate<br>        cashback = Int(Double(cost) * cashRebate)<br>        treepointback = Int(Double(cost) * treepointRebate)<br>        <br>        let totalDiscount = openpointback + Double(treepointback) + Double(cashback)<br>        <br>        return totalDiscount<br>    }</pre><blockquote>加滿按鈕 計算回饋金功能</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*d1Q4VPED67jNSAWub-vRTg.gif" /><figcaption>加好加滿 回饋金拿滿</figcaption></figure><pre>@IBAction func calculateFillupFuelCostBtn(_ sender: Any) {<br>        if let fuelTank = Double(carFuelTankTextField.text!),<br>           let cost = Double(costTextField.text!),<br>           fuelTank &gt; 0, cost &gt; 0 {<br>            let totalDiscount = calculateRebate(cost: Int(fuelCost))<br>            let fuelLiterMessage = &quot;本次加油量： &quot; + String(format: &quot;%.2f&quot;, fuelLiter)+&quot;公升\n&quot;<br>            let costMessage = &quot;花費金額： &quot; + String(format: &quot;%.f&quot;, fuelCost)+&quot;元\n&quot;<br>            let discountMessage = &quot;總回饋金額(&quot; + String(format: &quot;%.2f&quot;,(( openpointRebate+cashRebate+treepointRebate)*100)) + &quot;%)： &quot; + String(format: &quot;%.2f&quot;, totalDiscount) + &quot;元\n&quot;<br>            let openpointMessage = &quot;OP點數回饋(&quot; + String(format: &quot;%.1f&quot;,openpointRebate*100) + &quot;%)： &quot; + String(format: &quot;%.2f&quot;, openpointback) + &quot;點\n&quot;<br>            let cachbackMessage = &quot;信用卡回饋金(\(cashRebate*100)%)： \(cashback)元\n&quot;<br>            let treepointMessage = &quot;小樹點回饋(\(treepointRebate*100)%)： \(treepointback)點\n&quot;<br>            let message = fuelLiterMessage + costMessage + discountMessage + openpointMessage + cachbackMessage + treepointMessage + payMessage<br>            let alertController = UIAlertController(title: &quot;\(gasName) 加滿&quot;, message: message , preferredStyle: .alert)<br>            let okAction = UIAlertAction(title: &quot;確定&quot;, style: .default){ _ in<br>                self.cashback = 0<br>                self.openpointback = 0.0<br>                self.treepointback = 0<br>                self.openpointRebate = 0.01<br>                self.cashRebate = 0.0<br>                self.treepointRebate = 0.0<br>                self.payMessage = &quot;支付方式:icash Pay、icash2.0、icash2.0聯名卡&quot;<br>            }<br>            alertController.addAction(okAction)<br>            present(alertController, animated: true)<br>        }<br>    }</pre><blockquote>自訂加油金額按鈕 計算回饋金功能</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*RnXU1aOyyaFRvq_XlcOKAg.gif" /><figcaption>自訂加油金額 回饋精算師</figcaption></figure><pre>@IBAction func calculateFuelCost(_ sender: Any) {<br>        <br>        if let cost = Double(costTextField.text!), cost &gt; 0{<br>            let totalDiscount = calculateRebate(cost: Int(cost))<br>            let fuelLiterMessage = &quot;本次加油量： &quot; + String(format: &quot;%.2f&quot;, fuelLiter)+&quot;公升\n&quot;<br>            let costMessage = &quot;花費金額： &quot; + String(format: &quot;%.f&quot;, cost)+&quot;元\n&quot;<br>            let discountMessage = &quot;總回饋金額(\((openpointRebate+cashRebate+treepointRebate)*100)%)： &quot; + String(format: &quot;%.2f&quot;, totalDiscount) + &quot;元\n&quot;<br>            let openpointMessage = &quot;OP點數回饋(&quot; + String(format: &quot;%.1f&quot;,openpointRebate*100) + &quot;%)： &quot; + String(format: &quot;%.2f&quot;, openpointback) + &quot;點\n&quot;<br>            let cachbackMessage = &quot;信用卡回饋金(\(cashRebate*100)%)： \(cashback)元\n&quot;<br>            let treepointMessage = &quot;小樹點回饋(\(treepointRebate*100)%)： \(treepointback)點\n&quot;<br>            let message = fuelLiterMessage + costMessage + discountMessage + openpointMessage + cachbackMessage + treepointMessage + payMessage<br>            <br>                let alertController = UIAlertController(title: &quot;\(gasName) 加\(Int(cost))元&quot;, message: message, preferredStyle: .alert)<br>                let okAction = UIAlertAction(title: &quot;確定&quot;, style: .default){ _ in<br>                    self.cashback = 0<br>                    self.openpointback = 0.0<br>                    self.treepointback = 0<br>                    self.openpointRebate = 0.01<br>                    self.cashRebate = 0.0<br>                    self.treepointRebate = 0.0<br>                    self.payMessage = &quot;支付方式:icash Pay、icash2.0、icash2.0聯名卡&quot;<br>                }<br>                alertController.addAction(okAction)<br>                present(alertController, animated: true)<br>        }<br>    }</pre><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/%E5%B0%8F%E8%B2%BB-app-%E5%BD%BC%E5%BE%97%E6%BD%98%E7%9A%84-ios-app-%E4%BD%9C%E6%A5%AD-89c3a831f82c">#35 換算 App，比方小費，BMI，BMR，匯率，單位換算</a></li><li><a href="https://anny86023.medium.com/swift-%E4%B8%B2%E6%8E%A5api-%E8%A7%A3%E6%9E%90xml-%E8%B3%87%E6%96%99-2a5fd3770884">Swift — 串接API &amp; 解析XML 資料</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61aa8e9dbf6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/20-%E6%8F%9B%E7%AE%97-app-%E5%8A%A0%E6%B2%B9%E8%B2%BB-%E5%9B%9E%E9%A5%8B%E9%87%91%E8%A8%88%E7%AE%97%E6%A9%9F-d61aa8e9dbf6">#20 換算 App 加油費&amp;回饋金計算機</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[#19 使用 IBOutlet，IBAction & 亂數創作全民打棒球抽卡app]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/19-%E4%BD%BF%E7%94%A8-iboutlet-ibaction-%E4%BA%82%E6%95%B8%E5%89%B5%E4%BD%9C%E5%85%A8%E6%B0%91%E6%89%93%E6%A3%92%E7%90%83%E6%8A%BD%E5%8D%A1-521214da64c4?source=rss-ecffe12b9c07------2</link>
            <guid isPermaLink="false">https://medium.com/p/521214da64c4</guid>
            <dc:creator><![CDATA[Lou]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 14:32:48 GMT</pubDate>
            <atom:updated>2023-05-17T04:19:47.199Z</atom:updated>
            <content:encoded><![CDATA[<p>紀念逝去的台版BBO</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*tf2DGBKwAdyoNULD8kR75g.gif" /><figcaption>現代貝比魯斯 世界的大谷翔平</figcaption></figure><blockquote>SetCardViewController 篩選抽卡畫面</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*3BFl2SOa6wsOSruFLyJxXA.gif" /><figcaption>首頁隨機圖片</figcaption></figure><pre>import UIKit<br>import AVFoundation<br><br>    let player = AVPlayer()<br>    var timer: Timer?<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        //播放BBO背景音樂<br>        let url = Bundle.main.url(/service/forresource: &quot;my-hero&quot;, withExtension: &quot;mp3&quot;)!<br>        let playerItem = AVPlayerItem(url: url)<br>        player.replaceCurrentItem(with: playerItem)<br>        player.play()<br>        //漸層背景<br>        setupGradientBackground()<br>        //標題旋轉<br>        titleLabel.transform = CGAffineTransform(rotationAngle: -.pi / 80)<br>        //初始球員卡圖片<br>        initialImageView()<br>        //設定Silder Thumb圖案<br>        hitValueSilder.setThumbImage(UIImage(systemName: &quot;baseball.fill&quot;), for: .normal)<br>        //利用timer隨機替換圖片<br>        timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(changeImageView), userInfo: nil, repeats: true)<br><br>    }<br><br>    //漸層背景<br>    func setupGradientBackground() {<br>        let gradientLayer = CAGradientLayer()<br>        gradientLayer.frame = view.bounds<br>        gradientLayer.colors = [<br>            CGColor(red: 1, green: 216/255, blue: 118/255, alpha: 1),<br>            UIColor.white.cgColor<br>        ]<br>        view.layer.insertSublayer(gradientLayer, at: 0)<br>    }<br>    <br>    <br>//利用shuffle隨機替換圖片<br>    @objc func changeImageView(){<br>        playerImageArray.shuffle()<br>        initialImageView()<br>    }<br>    <br>//設定圖片<br>    func initialImageView(){<br>        player1ImageView.image = UIImage(named: playerImageArray[0])<br>        player2ImageView.image = UIImage(named: playerImageArray[1])<br>        player3ImageView.image = UIImage(named: playerImageArray[2])<br>    }<br><br>//鍵盤按下return收鍵盤<br>    @IBAction func returnCloseKeyboard(_ sender: Any) {<br>        <br>    }<br>//點選空白處收鍵盤<br>    @IBAction func closeKeyboard(_ sender: Any) {<br>        view.endEditing(true)<br>    }</pre><h4>斜角ImageView &amp; View</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*PYzziVq6QFJLFxzyrZlOZg.png" /><figcaption>抽一波</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*ArXRL7DNPoB980xcYtZBJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*n7HlTuiEJ5sUkmOYolyhdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*PaTujLdDN8_VYjJlm46-Ig.png" /><figcaption>建立SharpView SharpView</figcaption></figure><pre>import UIKit<br><br>//斜角效果的View<br>class SharpView: UIView {<br>    <br>    override func layoutSubviews() {<br>        super.layoutSubviews()<br>        let path = UIBezierPath()<br>        path.move(to: CGPoint(x: 0, y: bounds.height * 0.2))<br>        path.addLine(to: CGPoint(x: bounds.width, y: 0))<br>        path.addLine(to: CGPoint(x: bounds.width, y:bounds.height))<br>        path.addLine(to: CGPoint(x: 0, y: bounds.height))<br>        path.close()<br>        let shapeLayer = CAShapeLayer()<br>        shapeLayer.path = path.cgPath<br>        layer.mask = shapeLayer<br>    }<br><br><br>import UIKit<br>//斜角效果的ImageView<br>class SharpView: UIImageView {<br>    <br>    override func layoutSubviews() {<br>        super.layoutSubviews()<br>        let path = UIBezierPath()<br>        path.move(to: CGPoint(x: bounds.width * 0.2, y: 0))<br>        path.addLine(to: CGPoint(x: bounds.width, y: 0))<br>        path.addLine(to: CGPoint(x: bounds.width * 0.8, y:bounds.height))<br>        path.addLine(to: CGPoint(x: 0, y: bounds.height))<br>        path.close()<br>        let shapeLayer = CAShapeLayer()<br>        shapeLayer.path = path.cgPath<br>        layer.mask = shapeLayer<br>        <br>    }</pre><h4>Silder篩選球員卡能力類型</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*sUfWOOkKOUsU5jvIggoN6Q.gif" /><figcaption>Slider滑動顯示類型</figcaption></figure><pre><br>//滑動Slider顯示不同類型<br>    @IBAction func changeHitValue(_ sender: UISlider) {<br>        if hitValueSilder.value &gt; 20 {<br>            hitLabel.text = &quot;&quot;<br>            hitPowerLabel.text = &quot;力量型&quot;<br>            hitContactLabel.text = &quot;&quot;<br>        } else if hitValueSilder.value &lt; 10{<br>            hitLabel.text = &quot;&quot;<br>            hitPowerLabel.text = &quot;&quot;<br>            hitContactLabel.text = &quot;打擊型&quot;<br>        } else {<br>            hitLabel.text = &quot;隨機&quot;<br>            hitPowerLabel.text = &quot;&quot;<br>            hitContactLabel.text = &quot;&quot;<br>        }<br>    }</pre><p>篩選條件功能</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*f4bZJa9CZ1GBE6m-Vvt9Yw.gif" /><figcaption>篩選生日條件</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*E42HFt81P3K9sAGpFdLrGg.gif" /><figcaption>篩選守位 聯盟 能力條件</figcaption></figure><pre> @IBAction func filter(_ sender: Any) {<br>        //生日條件只能單獨篩選<br>        if dateSwitch.isOn {<br>            //提示視窗<br>            let alertController = UIAlertController(title: &quot;啟用生日篩選球員卡&quot;, message: &quot;只能單獨篩選生日條件，不能加入其他篩選條件。&quot;, preferredStyle: .alert)<br>            let okAction = UIAlertAction(title: &quot;確定啟用&quot;, style: .default)<br>            let cancelAction = UIAlertAction(title: &quot;取消篩選&quot;, style: .cancel){ _ in<br>                self.dateSwitch.isOn = false<br>            }<br>            alertController.addAction(okAction)<br>            alertController.addAction(cancelAction)<br>            present(alertController, animated: true)<br>            //其他條件變成初始隨機<br>            hitValueSilder.value = 15<br>            positionSegmentedControl.selectedSegmentIndex = 0<br>            leagueSegmentedControl.selectedSegmentIndex = 0<br>        }<br>        <br>        //篩選條件最多兩項 超過跳出提示視窗<br>        if hitValueSilder.value &lt; 10 || hitValueSilder.value &gt; 20, positionSegmentedControl.selectedSegmentIndex != 0, leagueSegmentedControl.selectedSegmentIndex != 0 {<br>            let alertController = UIAlertController(title: &quot;球員卡篩選限制&quot;, message: &quot;守位、聯盟、能力 3項條件，最多只能設定 2個項目！&quot;, preferredStyle: .alert)<br>            let cancelAction = UIAlertAction(title: &quot;重新設定&quot;, style: .cancel)<br>            alertController.addAction(cancelAction)<br>            present(alertController, animated: true)<br>            hitValueSilder.value = 15<br>            hitLabel.text = &quot;隨機&quot;<br>            hitPowerLabel.text = &quot;&quot;<br>            hitContactLabel.text = &quot;&quot;<br>            positionSegmentedControl.selectedSegmentIndex = 0<br>            leagueSegmentedControl.selectedSegmentIndex = 0<br>        }<br><br>    //重置篩選條件<br>    @IBAction func resetRule(_ sender: Any) {<br>        nameTextField.text = &quot;&quot;<br>        birthdayDatePicker.date = NSDate() as Date<br>        dateSwitch.isOn = false<br>        hitValueSilder.value = 15<br>        hitLabel.text = &quot;隨機&quot;<br>        hitPowerLabel.text = &quot;&quot;<br>        hitContactLabel.text = &quot;&quot;<br>        positionSegmentedControl.selectedSegmentIndex = 0<br>        leagueSegmentedControl.selectedSegmentIndex = 0<br>    }</pre><p>傳遞資料到下一頁</p><pre>@IBSegueAction func setRules(_ coder: NSCoder) -&gt; GetCardViewController? {<br>        //關掉隨機圖片timer<br>        timer?.invalidate()<br>        let name = String(nameTextField.text!)<br>        //傳遞生日篩選條件的月份<br>        let dateComponents = Calendar.current.dateComponents(in: TimeZone.current, from: birthdayDatePicker.date)<br>        var month = 0<br>        if dateSwitch.isOn {<br>            //開啟篩選生日switch才有資料<br>            month = Int(dateComponents.month!)<br>        }<br>        let hitValue = Float(hitValueSilder.value)<br>        let position = Int(positionSegmentedControl.selectedSegmentIndex)<br>        let league = Int(leagueSegmentedControl.selectedSegmentIndex)<br>        <br>        let controller = GetCardViewController(coder: coder)<br>    <br>        controller?.userName = name<br>        controller?.month = month<br>        controller?.hitValue = hitValue<br>        controller?.positionIndex = position<br>        controller?.leagueIndex = league<br>        controller?.playerSeconds = playerSeconds<br>    <br>        return controller<br>    }</pre><blockquote>GetCardViewController抽球員卡拉霸頁面</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*1WEG40WbVqWrwb4DUgek-g.gif" /><figcaption>拉霸抽卡</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMp_46OkwzgC6E43DGO4rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*yzkh54LXcbjpIAp0hI-WJQ.png" /><figcaption>Scroll View + Stack View</figcaption></figure><p>利用Scroll View捲動效果 放入超過View大小的Stack View</p><p>再利用程式滾動+圖片替換達成拉霸抽卡效果</p><pre>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        //背景漸層<br>        setupGradientBackground()<br>        //加入篩選後球員卡<br>        addPlayerCard()<br>        //球員卡洗牌<br>        shuffleCard()<br>        //設定初始四張球員卡圖片<br>        initialCard()<br>        //捲動球員卡拉霸效果<br>        autoScroll()<br>    }<br><br>    //背景漸層<br>    func setupGradientBackground() {<br>        let gradientLayer = CAGradientLayer()<br>        gradientLayer.frame = view.bounds<br>        gradientLayer.colors = [<br>            CGColor(red: 1, green: 216/255, blue: 118/255, alpha: 1),<br>            UIColor.white.cgColor<br>        ]<br>        view.layer.insertSublayer(gradientLayer, at: 0)<br>    }<br>    <br>    //設定初始四張球員卡圖片<br>    func initialCard(){<br>        playerCard1ImageView.image = UIImage(named: randomPlayerCardArray[0])<br>        playerCard2ImageView.image = UIImage(named: randomPlayerCardArray[1])<br>        playerCard3ImageView.image = UIImage(named: randomPlayerCardArray[2])<br>        playerCard4ImageView.image = UIImage(named: randomPlayerCardArray[3])<br>    }</pre><p>滾動Scroll View功能</p><pre>    var timer: Timer?<br>    var scrollDistance = 0<br>    var changeCardCount = 0<br>    var rounds = 3<br>    var scrollSpeed = 0.05<br><br>   func autoScroll(){<br>        timer = Timer.scheduledTimer(timeInterval: scrollSpeed, target: self, selector: #selector(randomCard), userInfo: nil, repeats: true)<br>    }<br><br>@objc func randomCard() {<br>        //畫面顯示imageView編號123 滾動顯示編號234 再變回初始顯示編號123<br>        //scrollView滾動1張imageView的距離<br>        if scrollDistance == 220{<br>            scrollDistance = 0<br>            randomCardScrollView.contentOffset.y = CGFloat(scrollDistance)<br>            changeCardCount += 1<br>            //array剩下倒數三張 將第4張imageView改成array[0]<br>            if changeCardCount == randomPlayerCardArray.count - 3{<br>                playerCard1ImageView.image = UIImage(named: randomPlayerCardArray[randomPlayerCardArray.count - 3])<br>                playerCard2ImageView.image = UIImage(named: randomPlayerCardArray[randomPlayerCardArray.count - 2])<br>                playerCard3ImageView.image = UIImage(named: randomPlayerCardArray[randomPlayerCardArray.count - 1])<br>                playerCard4ImageView.image = UIImage(named: randomPlayerCardArray[0])<br>                //將第3張imageView改成array[0] 第4張改成array[1]<br>            }else if changeCardCount == randomPlayerCardArray.count - 2{<br>                playerCard1ImageView.image = UIImage(named: randomPlayerCardArray[randomPlayerCardArray.count - 2])<br>                playerCard2ImageView.image = UIImage(named: randomPlayerCardArray[randomPlayerCardArray.count - 1])<br>                playerCard3ImageView.image = UIImage(named: randomPlayerCardArray[0])<br>                playerCard4ImageView.image = UIImage(named: randomPlayerCardArray[1])<br>                //將第2張imageView改成array[0] 第3張改成array[1] 第4張改成array[2]<br>            }else if changeCardCount == randomPlayerCardArray.count - 1{<br>                playerCard1ImageView.image = UIImage(named: randomPlayerCardArray[randomPlayerCardArray.count - 1])<br>                playerCard2ImageView.image = UIImage(named: randomPlayerCardArray[0])<br>                playerCard3ImageView.image = UIImage(named: randomPlayerCardArray[1])<br>                playerCard4ImageView.image = UIImage(named: randomPlayerCardArray[2])<br>                //將第1張imageView改成array[0] 第2張改成array[1] 第3張改成array[2] 變回初始才有重複輪盤效果<br>            }else if changeCardCount == randomPlayerCardArray.count {<br>                changeCardCount = 0<br>                rounds -= 1<br>                initialCard()<br>            }else{<br>                //依序放入array球員卡imageView<br>                playerCard1ImageView.image = UIImage(named: randomPlayerCardArray[changeCardCount])<br>                playerCard2ImageView.image = UIImage(named: randomPlayerCardArray[changeCardCount + 1])<br>                playerCard3ImageView.image = UIImage(named: randomPlayerCardArray[changeCardCount + 2])<br>                playerCard4ImageView.image = UIImage(named: randomPlayerCardArray[changeCardCount + 3])<br>            }<br>            <br>        }else{<br>            //scrollView每次滾動的距離<br>            scrollDistance += 55<br>            randomCardScrollView.contentOffset.y = CGFloat(scrollDistance)<br>        }<br>        <br>        //三次的滾動速度漸漸變緩<br>        switch rounds{<br>            case 0:<br>                timer?.invalidate()<br>            case 1:<br>                timer?.invalidate()<br>                scrollSpeed = 0.2<br>                autoScroll()<br>            case 2:<br>                timer?.invalidate()<br>                scrollSpeed = 0.1<br>                autoScroll()<br>            default:<br>                break<br>        }<br>        <br>        //跑完滾動次數 顯示抽到的球員卡<br>        if rounds == 0 {<br>            let playerSeconds = player.currentTime().seconds<br>            player.pause()<br>            if let controller = storyboard?.instantiateViewController(withIdentifier: &quot;AlertView&quot;) as? AlertViewController{<br>                controller.playerSeconds = playerSeconds<br>                controller.userName = userName<br>                controller.playerCardArray = randomPlayerCardArray<br>                present(controller, animated: true)<br>            }<br>        }<br>    }<br></pre><p>建立struct PlayerCard 球員卡資料字典</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eAR4w9XqqK7KG0rV5swylQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1sCdc2PkB2R-6ipSfQqOYw.png" /></figure><p>加入篩選後的球員卡</p><p>改進後寫法：</p><pre>    func filterPlayerCards() -&gt; [String] {<br>        let filteredCards = playerCards.filter { card in<br>            switch positionIndex {<br>            case 1:<br>                if !card.position.contains(&quot;內野&quot;) { return false }<br>            case 2:<br>                if !card.position.contains(&quot;外野&quot;) { return false }<br>            default:<br>                break<br>            }<br>            <br>            switch leagueIndex {<br>            case 1:<br>                if card.league != &quot;AL&quot; &amp;&amp; card.league != &quot;NL&quot; { return false }<br>            case 2:<br>                if card.league == &quot;AL&quot; || card.league == &quot;NL&quot; { return false }<br>            default:<br>                break<br>            }<br>            <br>            switch Int(hitValue) {<br>            case ..&lt;10:<br>                if card.hitType != &quot;打擊型&quot; { return false }<br>            case 20...:<br>                if card.hitType != &quot;力量型&quot; { return false }<br>            default:<br>                break<br>            }<br>            <br>            switch month {<br>            case 1, 2, 3:<br>                if card.birthday &gt; 3 { return false }<br>            case 4, 5, 6:<br>                if card.birthday &lt; 4 || card.birthday &gt; 6 { return false }<br>            case 7, 8, 9:<br>                if card.birthday &lt; 7 || card.birthday &gt; 9 { return false }<br>            case 10, 11, 12:<br>                if card.birthday &lt; 10 || card.birthday &gt; 12 { return false }<br>            default:<br>                break<br>            }<br>            <br>            return true<br>        }<br>        return filteredCards.map { $0.imageName }<br>    }<br>    <br>    func addPlayerCard() {<br>        playerCardArray = filterPlayerCards()<br>    }</pre><p>原本寫法：</p><pre>    <br>    var month: Int!<br>    var hitValue: Float!<br>    var positionIndex: Int!<br>    var leagueIndex: Int!<br>    var playerCardArray = [String]()<br><br>    func addPlayerCard(){<br>        //先篩選球員卡守備位置<br>        switch positionIndex {<br>        case 1:<br>            for i in 0..&lt;playerCards.count {<br>                //篩選MLB內野球員卡<br>                if leagueIndex == 1 {<br>                    if playerCards[i].position.contains(&quot;內野&quot;), playerCards[i].league == &quot;AL&quot; || playerCards[i].league == &quot;NL&quot; {<br>                        playerCardArray.append(playerCards[i].imageName)<br>                    }<br>                    //篩選台灣內野球員卡<br>                } else if leagueIndex == 2 {<br>                    if playerCards[i].position.contains(&quot;內野&quot;), playerCards[i].league != &quot;AL&quot;, playerCards[i].league != &quot;NL&quot; {<br>                        playerCardArray.append(playerCards[i].imageName)<br>                    }<br>                    //篩選打擊型內野球員卡<br>                } else if hitValue &lt; 10 {<br>                    if playerCards[i].position.contains(&quot;內野&quot;), playerCards[i].hitType == &quot;打擊型&quot; {<br>                        playerCardArray.append(playerCards[i].imageName)<br>                    }<br>                    //篩選力量型內野球員卡<br>                } else if hitValue &gt; 20{<br>                    if playerCards[i].position.contains(&quot;內野&quot;), playerCards[i].hitType == &quot;力量型&quot; {<br>                        playerCardArray.append(playerCards[i].imageName)<br>                    }<br>                    //只篩選內野球員卡<br>                }else{<br>                    if playerCards[i].position.contains(&quot;內野&quot;) {<br>                        playerCardArray.append(playerCards[i].imageName)<br>                    }<br>                }<br>            }<br>        case 2:<br>            for i in 0..&lt;playerCards.count {<br>                //篩選MLB外野球員卡<br>                if leagueIndex == 1 {<br>                    if playerCards[i].position.contains(&quot;外野&quot;), playerCards[i].league == &quot;AL&quot; || playerCards[i].league == &quot;NL&quot; {<br>                        playerCardArray.append(playerCards[i].imageName)<br>                    }<br>                    //篩選台灣外野球員卡<br>                } else if leagueIndex == 2 {<br>                    if playerCards[i].position.contains(&quot;外野&quot;), playerCards[i].league != &quot;AL&quot;, playerCards[i].league != &quot;NL&quot; {<br>                        playerCardArray.append(playerCards[i].imageName)<br>                    }<br>                    //篩選打擊型外野球員卡<br>                } else if hitValue &lt; 10 {<br>                    if playerCards[i].position.contains(&quot;外野&quot;), playerCards[i].hitType == &quot;打擊型&quot; {<br>                        playerCardArray.append(playerCards[i].imageName)<br>                    }<br>                    //篩選力量型外野球員卡<br>                } else if hitValue &gt; 20{<br>                    if playerCards[i].position.contains(&quot;外野&quot;), playerCards[i].hitType == &quot;力量型&quot; {<br>                        playerCardArray.append(playerCards[i].imageName)<br>                    }<br>                    //只篩選外野球員卡<br>                }else{<br>                    if playerCards[i].position.contains(&quot;外野&quot;) {<br>                        playerCardArray.append(playerCards[i].imageName)<br>                    }<br>                }<br>            }<br>        default:<br>            //剩下篩選球員卡聯盟<br>            switch leagueIndex {<br>            case 1:<br>                for i in 0..&lt;playerCards.count {<br>                    //篩選MLB打擊型球員卡<br>                    if hitValue &lt; 10{<br>                        if playerCards[i].league == &quot;AL&quot; || playerCards[i].league == &quot;NL&quot;, playerCards[i].hitType == &quot;打擊型&quot;{<br>                            playerCardArray.append(playerCards[i].imageName)<br>                        }<br>                        //篩選MLB力量型球員卡<br>                    } else if hitValue &gt; 20 {<br>                        if playerCards[i].league == &quot;AL&quot; || playerCards[i].league == &quot;NL&quot;, playerCards[i].hitType == &quot;力量型&quot;{<br>                            playerCardArray.append(playerCards[i].imageName)<br>                        }<br>                        //篩選MLB球員卡<br>                    } else {<br>                        if playerCards[i].league == &quot;AL&quot; || playerCards[i].league == &quot;NL&quot; {<br>                            playerCardArray.append(playerCards[i].imageName)<br>                        }<br>                    }<br>                }<br>            case 2:<br>                for i in 0..&lt;playerCards.count {<br>                    //篩選台灣打擊型球員卡<br>                    if hitValue &lt; 10{<br>                        if playerCards[i].league != &quot;AL&quot;, playerCards[i].league != &quot;NL&quot;, playerCards[i].hitType == &quot;打擊型&quot;{<br>                            playerCardArray.append(playerCards[i].imageName)<br>                        }<br>                        //篩選台灣力量型球員卡<br>                    } else if hitValue &gt; 20 {<br>                        if playerCards[i].league != &quot;AL&quot;, playerCards[i].league != &quot;NL&quot;, playerCards[i].hitType == &quot;力量型&quot;{<br>                            playerCardArray.append(playerCards[i].imageName)<br>                        }<br>                        //篩選台灣球員卡<br>                    } else {<br>                        if playerCards[i].league != &quot;AL&quot;, playerCards[i].league != &quot;NL&quot; {<br>                            playerCardArray.append(playerCards[i].imageName)<br>                        }<br>                    }<br>                }<br>            default:<br>                switch Int(hitValue){<br>                    //篩選打擊型球員卡<br>                case ..&lt;10:<br>                    for i in 0..&lt;playerCards.count {<br>                        if playerCards[i].hitType == &quot;打擊型&quot; {<br>                            playerCardArray.append(playerCards[i].imageName)<br>                        }<br>                    }<br>                    //篩選力量型球員卡<br>                case 20...:<br>                    for i in 0..&lt;playerCards.count {<br>                        if playerCards[i].hitType == &quot;力量型&quot; {<br>                            playerCardArray.append(playerCards[i].imageName)<br>                        }<br>                    }<br>                    <br>                default:<br>                    //無篩選條件<br>                    for i in 0..&lt;playerCards.count {<br>                        playerCardArray.append(playerCards[i].imageName)<br>                    }<br>                }<br>            }<br>            <br>        }<br>        <br>        //篩選球員卡生日月份<br>        switch month {<br>        case 1, 2 ,3:<br>            for i in 0...playerCards.count - 1 {<br>                if playerCards[i].birthday &gt;= 1 ,playerCards[i].birthday &lt;= 3 {<br>                    playerCardArray.append(playerCards[i].imageName)<br>                }<br>            }<br>        case 4, 5 ,6:<br>            for i in 0...playerCards.count - 1 {<br>                if playerCards[i].birthday &gt;= 4 ,playerCards[i].birthday &lt;= 6 {<br>                    playerCardArray.append(playerCards[i].imageName)<br>                }<br>            }<br>        case 7, 8 ,9:<br>            for i in 0...playerCards.count - 1 {<br>                if playerCards[i].birthday &gt;= 7 ,playerCards[i].birthday &lt;= 9 {<br>                    playerCardArray.append(playerCards[i].imageName)<br>                }<br>            }<br>        case 10, 11 ,12:<br>            for i in 0...playerCards.count - 1{<br>                if playerCards[i].birthday &gt;= 10 ,playerCards[i].birthday &lt;= 12 {<br>                    playerCardArray.append(playerCards[i].imageName)<br>                }<br>            }<br>        default:<br>            break<br>        }<br>    }</pre><p>篩選後洗牌功能</p><pre>    var randomPlayerCardArray = [String]()<br><br>    func shuffleCard(){<br>        //超過１０張再篩選(節省拉霸轉盤時間)<br>        if playerCardArray.count &gt; 10{<br>            playerCardArray = playerCardArray.shuffled()<br>            for i in 0...10{<br>                randomPlayerCardArray.append(playerCardArray[i])<br>            }<br>        }else{<br>            randomPlayerCardArray = playerCardArray.shuffled()<br>        }<br>        <br>    }</pre><p>回到上一頁重新抽卡</p><pre>    @IBAction func backSetPage(_ sender: Any) {<br>        <br>        if let controller = storyboard?.instantiateViewController(withIdentifier: &quot;SetCardView&quot;){<br>            timer?.invalidate()<br>            present(controller, animated: true)<br>        }<br>    }</pre><blockquote>AlertViewController顯示獲得的球員卡</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*sfYSQDivzS1g73Vp-nKWqQ.gif" /><figcaption>恭喜中獎！！</figcaption></figure><pre>import UIKit<br><br>class AlertViewController: UIViewController {<br>    <br>    var userName: String?<br>    var playerCardArray: [String]?<br>    var playerSeconds: Double!<br>    let player = AVPlayer()<br><br>    @IBOutlet weak var alertLabel: UILabel!<br>    @IBOutlet weak var playerCardView: UIImageView!<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        if let playerCardArray = self.playerCardArray{<br>            playerCardView.image = UIImage(named: playerCardArray[1])<br>        }<br>        if let userName = self.userName{<br>            alertLabel.text = &quot;恭喜\(userName)獲得球員卡&quot;<br>        } else {<br>            alertLabel.text = &quot;恭喜您獲得球員卡&quot;<br>        }<br>        <br>        <br>    }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=521214da64c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/19-%E4%BD%BF%E7%94%A8-iboutlet-ibaction-%E4%BA%82%E6%95%B8%E5%89%B5%E4%BD%9C%E5%85%A8%E6%B0%91%E6%89%93%E6%A3%92%E7%90%83%E6%8A%BD%E5%8D%A1-521214da64c4">#19 使用 IBOutlet，IBAction &amp; 亂數創作全民打棒球抽卡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[#18 撞球計分板(Scoreboard)]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/18-%E6%92%9E%E7%90%83%E8%A8%88%E5%88%86%E6%9D%BF-scoreboard-905d7b0324f3?source=rss-ecffe12b9c07------2</link>
            <guid isPermaLink="false">https://medium.com/p/905d7b0324f3</guid>
            <dc:creator><![CDATA[Lou]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 16:16:43 GMT</pubDate>
            <atom:updated>2023-03-23T04:06:08.059Z</atom:updated>
            <content:encoded><![CDATA[<p>製作撞球14-1規則的計分板</p><blockquote>SetViewController 資料傳遞到計分板畫面</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*qQgPhmVynviJ-1scSeL8rQ.gif" /><figcaption>可設定名稱 獲勝分數</figcaption></figure><pre>import UIKit<br><br>class SetViewController: UIViewController {<br><br>    @IBOutlet weak var playerATextField: UITextField!<br>    @IBOutlet weak var playerBTextField: UITextField!<br>    @IBOutlet weak var gameScoreTextField: UITextField!<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br><br>    }<br>    <br><br>    <br>    //點選空白處收鍵盤<br>    @IBAction func closeKeyboard(_ sender: Any) {<br>        view.endEditing(true)<br>    }<br>    <br>    //鍵盤按下return鍵收鍵盤<br>    @IBAction func returnCloseKeyboard(_ sender: Any) {<br>    }<br>    <br>    <br>    //segue傳遞資料到計分板頁面<br>    @IBSegueAction func showResult(_ coder: NSCoder) -&gt; ScoreViewController? {<br>        <br>        let setPlayerAName = String(playerATextField.text!)<br>        let setPlayerBName = String(playerBTextField.text!)<br>        let setGameScore = Int(gameScoreTextField.text!)<br><br>        let controller = ScoreViewController(coder: coder)<br>        <br>        controller?.playerAName = setPlayerAName<br>        controller?.playerBName = setPlayerBName<br>        controller?.gameScore = setGameScore<br>        <br>        <br>        return controller<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/%E9%80%A3%E7%B5%90-uitextfield-%E7%9A%84-did-end-on-exit-event-%E6%8C%89%E4%B8%8B-return-%E9%8D%B5%E6%94%B6%E9%8D%B5%E7%9B%A4-5b3f2f4aeb03">連結 UITextField 的 Did End On Exit event，按下 return 鍵收鍵盤</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/uikit-app-%E6%8C%89%E7%A9%BA%E7%99%BD%E8%99%95%E6%94%B6%E9%8D%B5%E7%9B%A4%E7%9A%84%E6%96%B9%E6%B3%95-97a676338e86">UIKit App 按空白處收鍵盤的方法</a></li></ul><blockquote>ScoreViewController 計分板介面</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*qdsjLHFzX-TAcRZrocNSYw.png" /><figcaption>計分板介面</figcaption></figure><h4>計時功能</h4><pre>var timer: Timer?<br>var counter = 0<br><br> override func viewDidLoad() {<br>        super.viewDidLoad()<br>    <br>        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)<br>        <br>    }<br>    <br>    @objc func updateTime(){<br>        counter += 1<br>        timeLabel.text = formatedTime(counter)<br>    }<br><br>//顯示時間格式<br>    func formatedTime(_ seconds: Int) -&gt; String {<br>        var hourSting = String()<br>        var minString = String()<br>        var secString = String()<br>        <br>        if seconds / 3600 == 0 {<br>            hourSting = &quot;00&quot;<br>        } else if (seconds / 3600 &gt; 0 &amp;&amp; seconds / 3600 &lt; 10 ){<br>            hourSting = &quot;0\(seconds / 3600)&quot;<br>        } else {<br>            hourSting = &quot;\(seconds / 3600)&quot;<br>        }<br>        <br>        if seconds / 60 == 0 {<br>            minString = &quot;00&quot;<br>        } else if (seconds / 60 &gt; 0 &amp;&amp; seconds / 60 &lt; 10){<br>            minString = &quot;0\(seconds / 60)&quot;<br>        } else {<br>            minString = &quot;\(seconds / 60)&quot;<br>        }<br>        <br>        if seconds % 60 == 0 {<br>            secString = &quot;00&quot;<br>        } else if (seconds % 60 &lt; 10){<br>            secString = &quot;0\(seconds % 60)&quot;<br>        } else {<br>            secString = &quot;\(seconds % 60)&quot;<br>        }<br>            <br>        return &quot;比賽時間:\n\(hourSting):\(minString):\(secString)&quot;<br><br>    }<br></pre><h4>計分功能</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*lHKQ8FAngqoNaV283DIGXA.gif" /><figcaption>進球加分 犯規扣分 下一局統計總分</figcaption></figure><pre>    //A隊加分<br>    @IBAction func addScoreA(_ sender: Any) {<br>        <br>        //單局雙方合計未達13分直接計分<br>        if scoreA + scoreB &lt; 13 {<br>            scoreA += 1<br>            playerABallView.frame.origin.y = CGFloat(60 + 40 * scoreA)<br>       //Array紀錄得分扣分<br>            getScoreArray.append(playerAScore)<br>        } else if scoreA + scoreB &lt; 14 {<br>        //單局合計14分 計算雙方總分並顯示<br>            scoreA += 1<br>            playerABallView.frame.origin.y = CGFloat(60 + 40 * scoreA)<br>            roundScoreA = roundScoreA + scoreA - foulScoreA<br>            roundScoreB = roundScoreB + scoreB - foulScoreB<br>            scoreALabel.text = roundScoreA.formatted()<br>            scoreBLabel.text = roundScoreB.formatted()<br>            getScoreArray.append(playerAScore)<br>        }<br>        //有設定獲勝分數 達標後會有獲勝提示<br>        if gameScore != nil &amp;&amp; gameScore &gt; 0{<br>            if scoreA + scoreB &lt; 14 &amp;&amp; (roundScoreA + scoreA - foulScoreA) == gameScore {<br>                showWinner()<br>            } else if scoreA + scoreB == 14 &amp;&amp; roundScoreA == gameScore {<br>                showWinner()<br>            }<br>        <br>        <br>    }<br>    <br>   //B隊加分<br>    @IBAction func addScoreB(_ sender: Any) {<br>        <br>        if scoreA + scoreB &lt; 13 {<br>            scoreB += 1<br>            playerBBallView.frame.origin.y = CGFloat(60 + 40 * scoreB)<br>            getScoreArray.append(playerBScore)<br>        } else if scoreA + scoreB &lt; 14 {<br>            scoreB += 1<br>            playerBBallView.frame.origin.y = CGFloat(60 + 40 * scoreB)<br>            roundScoreA = roundScoreA + scoreA - foulScoreA<br>            roundScoreB = roundScoreB + scoreB - foulScoreB<br>            scoreALabel.text = roundScoreA.formatted()<br>            scoreBLabel.text = roundScoreB.formatted()<br>            getScoreArray.append(playerBScore)<br>        }<br>        <br>        if gameScore != nil &amp;&amp; gameScore &gt; 0{<br>            if scoreA + scoreB &lt; 14 &amp;&amp; (roundScoreB + scoreB - foulScoreB) == gameScore {<br>                showWinner()<br>            } else if scoreA + scoreB == 14 &amp;&amp; roundScoreB == gameScore {<br>                showWinner()<br>            }<br>        }<br>    }<br><br>    //A隊犯規扣分<br>    @IBAction func reduceScoreA(_ sender: Any) {<br>        <br>        if scoreA + scoreB != 14 {<br>            foulScoreA += 1<br>            foulALabel.text = foulScoreA.formatted()<br>            getScoreArray.append(playerAFoul)<br>        }<br>    }<br>    <br>   <br>    //B隊犯規扣分<br>    @IBAction func reduceScoreB(_ sender: Any) {<br>        <br>        if scoreA + scoreB != 14 {<br>            foulScoreB += 1<br>            foulBLabel.text = foulScoreB.formatted()<br>            getScoreArray.append(playerBFoul)<br>        }<br>    }</pre><h4>下一局按鍵</h4><p>14-1打完球檯上14顆球 重新排球計分進入下一局</p><pre>    @IBAction func changeNextGame(_ sender: Any) {<br>        <br>        //達到雙方進球總和14分 重置單局分數及得分圖示初始位置<br>        if scoreA + scoreB == 14 {<br>            scoreA = 0<br>            scoreB = 0<br>            foulScoreA = 0<br>            foulScoreB = 0<br>            rounds += 1<br>            foulALabel.text = foulScoreA.formatted()<br>            foulBLabel.text = foulScoreB.formatted()<br>            playerABallView.frame.origin.y = CGFloat(60)<br>            playerBBallView.frame.origin.y = CGFloat(60)<br>            totalScoreAArray.append(roundScoreA)<br>            totalScoreBArray.append(roundScoreB)<br>            getScoreArray.removeAll()<br>        }<br>    }</pre><h4>恢復上一步功能</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*7Gj2lnSEwDmKNy9mKixCfQ.gif" /><figcaption>計分錯誤 可以恢復上ㄧ步</figcaption></figure><pre>@IBAction func rewind(_ sender: Any) {<br>        //利用Array.popLast找出最後一步的操作<br>        let lastScore = getScoreArray.popLast()<br>        //判斷條件後 恢復上一步<br>        switch lastScore {<br>            <br>        case playerAScore:<br>            if scoreA + scoreB == 14 {<br>                scoreA -= 1<br>                playerABallView.frame.origin.y = CGFloat(60 + 40 * scoreA)<br>                roundScoreA = totalScoreAArray[rounds]<br>                roundScoreB = totalScoreBArray[rounds]<br>                scoreALabel.text = roundScoreA.formatted()<br>                scoreBLabel.text = roundScoreB.formatted()<br>                <br>            } else {<br>                scoreA -= 1<br>                playerABallView.frame.origin.y = CGFloat(60 + 40 * scoreA)<br>            }<br>            <br>        case playerBScore:<br>            if scoreA + scoreB == 14 {<br>                scoreB -= 1<br>                playerBBallView.frame.origin.y = CGFloat(60 + 40 * scoreB)<br>                roundScoreA = totalScoreAArray[rounds]<br>                roundScoreB = totalScoreBArray[rounds]<br>                scoreALabel.text = roundScoreA.formatted()<br>                scoreBLabel.text = roundScoreB.formatted()<br>                <br>            } else {<br>                scoreB -= 1<br>                playerBBallView.frame.origin.y = CGFloat(60 + 40 * scoreB)<br>            }<br>            <br>        case playerAFoul:<br>            foulScoreA -= 1<br>            foulALabel.text = foulScoreA.formatted()<br>        <br>        case playerBFoul:<br>            foulScoreB -= 1<br>            foulBLabel.text = foulScoreB.formatted()<br>        <br>        default:<br>            break<br>        }</pre><h4>獲勝提示</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*JBgJLkIw55cueRL_lVbHlQ.gif" /><figcaption>分數達標 獲勝提示</figcaption></figure><pre>func showWinner(){<br>        var winnerName = String()<br>        //判斷雙方總分 <br>        if (roundScoreA + scoreA - foulScoreA) &gt; (roundScoreB + scoreB - foulScoreB) {<br>            winnerName = playerALabel.text!<br>        } else {<br>            winnerName = playerBLabel.text!<br>        }<br>    <br>        //使用UIAlert <br>        let controller = UIAlertController(title: &quot;恭喜\(winnerName)獲勝&quot;, message: &quot;🏆🏆🏆🏆🏆🏆&quot;, preferredStyle: .alert)<br>        let okAction = UIAlertAction(title: &quot;重置比賽&quot;, style: .default){<br>            _ in<br>        //重置比賽<br>            self.resetGame()<br>        }<br>        controller.addAction(okAction)<br>        present(controller, animated: true)<br>        <br>        }</pre><h4>重置比賽功能</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*fBkcTlj0-7NqIYcjv3zLMA.gif" /><figcaption>重置比賽</figcaption></figure><pre>func initialUI(){<br><br>         //SetViewController傳遞的資料如果空白 設為預設值<br>        if playerAName != &quot;&quot; {<br>            playerALabel.text = playerAName<br>        } else {<br>            playerALabel.text = &quot;A(先攻)&quot;<br>        }<br>        <br>        if playerBName != &quot;&quot;{<br>            playerBLabel.text = playerBName<br>        } else {<br>            playerBLabel.text = &quot;B(後攻)&quot;<br>        }<br>        <br>        if gameScore != nil {<br>            gameScoreLabel.text = &quot;獲勝總分:\( gameScore!.formatted())&quot;<br>        } else {<br>            gameScoreLabel.text = &quot;單局計分&quot;<br>        }<br>        <br>    }<br><br><br>//重置功能<br>func resetGame(){<br>        <br>        initialUI()<br>        rounds = 0<br>        scoreA = 0<br>        scoreB = 0<br>        foulScoreA = 0<br>        foulScoreB = 0<br>        roundScoreA = 0<br>        roundScoreB = 0<br>        totalScoreAArray = [0]<br>        totalScoreBArray = [0]<br>        scoreALabel.text = roundScoreA.formatted()<br>        scoreBLabel.text = roundScoreB.formatted()<br>        foulALabel.text = foulScoreA.formatted()<br>        foulBLabel.text = foulScoreB.formatted()<br>        playerABallView.frame.origin.y = CGFloat(60)<br>        playerBBallView.frame.origin.y = CGFloat(60)<br>        getScoreArray.removeAll()<br>        <br>    }<br><br><br>//建立重置UIAlert提示<br>@IBAction func reset(_ sender: Any) {<br>        <br>    let controller = UIAlertController(title: &quot;重置比賽&quot;, message: &quot;確定要重置比賽&quot;, preferredStyle: .alert)<br>    let okAction = UIAlertAction(title: &quot;確定&quot;, style: .default){ _ in<br>            self.resetGame()<br>        }<br>        controller.addAction(okAction)<br>        let cancelAction = UIAlertAction(title: &quot;取消&quot;, style: .cancel)<br>        controller.addAction(cancelAction)<br>        present(controller, animated: true)<br>        <br>    }</pre><blockquote>作品程式碼</blockquote><ul><li><a href="https://github.com/Lou1202/billiard14-1.git">GitHub - Lou1202/billiard14-1</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/154-%E6%A1%8C%E7%90%83%E8%A8%88%E5%88%86%E6%9D%BF-scoreboard-7e43c3a488b9">#154 桌球計分板(Scoreboard)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=905d7b0324f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/18-%E6%92%9E%E7%90%83%E8%A8%88%E5%88%86%E6%9D%BF-scoreboard-905d7b0324f3">#18 撞球計分板(Scoreboard)</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[#17 利用 page control，segmented control，button & gesture 更換內容]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/17-%E5%88%A9%E7%94%A8-page-control-segmented-control-button-gesture-%E6%9B%B4%E6%8F%9B%E5%85%A7%E5%AE%B9-140c5a4a3f81?source=rss-ecffe12b9c07------2</link>
            <guid isPermaLink="false">https://medium.com/p/140c5a4a3f81</guid>
            <dc:creator><![CDATA[Lou]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 13:11:18 GMT</pubDate>
            <atom:updated>2023-03-10T08:29:22.685Z</atom:updated>
            <content:encoded><![CDATA[<p>展示寶可夢朱紫隊伍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*UhCuvgjhu8ZqpoAGoW35wg.png" /><figcaption>元件介面</figcaption></figure><blockquote>定義陣列</blockquote><pre>//寶可夢圖片及名稱<br>let pokemonArray = [&quot;#1008 密勒頓&quot;, &quot;#1002 古劍豹&quot;, &quot;#992 鐵臂膀&quot;, &quot;#991 鐵包袱&quot;, &quot;#923 巴布土撥&quot;, &quot;#58 風速狗&quot;]<br>let segmentTitleArray = [&quot;密勒頓&quot;, &quot;古劍豹&quot;, &quot;鐵臂膀&quot;, &quot;鐵包袱&quot;, &quot;巴布土撥&quot;, &quot;風速狗&quot;]<br>let pokemonImageArray = [&quot;密勒頓&quot;, &quot;古劍豹&quot;, &quot;鐵臂膀&quot;, &quot;鐵包袱&quot;, &quot;巴布土撥&quot;, &quot;風速狗&quot;]<br>let pokemonShinyImageArray = [&quot;密勒頓閃光&quot;, &quot;古劍豹閃光&quot;, &quot;鐵臂膀閃光&quot;, &quot;鐵包袱閃光&quot;, &quot;巴布土撥閃光&quot;, &quot;風速狗閃光&quot;]<br><br>//寶可夢六項個體值<br>let hpValue = [100, 80, 154, 56, 70, 90]<br>let attackValue = [85, 120, 140, 80, 115, 110]<br>let defenseValue = [100, 80, 108, 114, 70, 80]<br>let spAttackValue = [135, 90, 50, 124, 70, 100]<br>let spDefenseValue = [115, 65, 68, 60, 60, 80]<br>let speedValue = [135, 135, 50, 136, 105, 95]</pre><blockquote>命名Outlet</blockquote><p>outlet 的名字一般會用名詞，且以元件的型別結尾。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*2A7nMPgvDaha7u2lHxFq1w.png" /></figure><blockquote>設定預設顯示畫面</blockquote><pre>override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Do any additional setup after loading the view.<br>        pokemonImageView.image = UIImage(named: pokemonImageArray[0])<br>        pokeLabel.text = pokemonArray[0]<br>        pageBot.currentPage = 0<br>        pokemonSegment.selectedSegmentIndex = 0<br>        <br>        //設定segment名稱<br>        for index in 0...5 {<br>            pokemonSegment.setTitle(segmentTitleArray[index], forSegmentAt: index)<br>        }<br>        <br>        //設定六項個體數值<br>        hpLabel.text = hpValue[0].formatted()<br>        attackLabel.text = attackValue[0].formatted()<br>        defenseLabel.text = defenseValue[0].formatted()<br>        spAttackLabel.text = spAttackValue[0].formatted()<br>        spDefenseLabel.text = spDefenseValue[0].formatted()<br>        speedLabel.text = speedValue[0].formatted()<br>        <br>        //設定個體質progressview 特別注意型別Float<br>        hpProgressView.progress = Float(hpValue[0])/upperLimit<br>        attackProgressView.progress = Float(attackValue[0])/upperLimit<br>        defenseProgressView.progress = Float(defenseValue[0])/upperLimit<br>        spAttackProgressView.progress = Float(speedValue[0])/upperLimit<br>        spDefenseProgressView.progress = Float(spDefenseValue[0])/upperLimit<br>        speedProgressView.progress = Float(speedValue[0])/upperLimit<br>        <br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*gQaChgW6djDdk3mmXhfHxA.png" /><figcaption>預設畫面內容</figcaption></figure><blockquote>建立可同步修改的function</blockquote><pre><br>    var num = 0<br>    let upperLimit:Float = 200<br><br>func sync() {<br>        pokemonImageView.image = UIImage(named: pokemonImageArray[num])<br>        pokeLabel.text = pokemonArray[num]<br>        pageBot.currentPage = num<br>        pokemonSegment.selectedSegmentIndex = num<br>        shinySwitch.isOn = false<br>        <br>        hpLabel.text = hpValue[num].formatted()<br>        attackLabel.text = attackValue[num].formatted()<br>        defenseLabel.text = defenseValue[num].formatted()<br>        spAttackLabel.text = spAttackValue[num].formatted()<br>        spDefenseLabel.text = spDefenseValue[num].formatted()<br>        speedLabel.text = speedValue[num].formatted()<br>        <br>        hpProgressView.progress = Float(hpValue[num])/upperLimit<br>        attackProgressView.progress = Float(attackValue[num])/upperLimit<br>        defenseProgressView.progress = Float(defenseValue[num])/upperLimit<br>        spAttackProgressView.progress = Float(speedValue[num])/upperLimit<br>        spDefenseProgressView.progress = Float(spDefenseValue[num])/upperLimit<br>        speedProgressView.progress = Float(speedValue[num])/upperLimit<br>        <br>    }</pre><blockquote>新增switch元件 顯示異色寶可夢功能</blockquote><pre>//異色寶可夢開關<br>    @IBAction func changeShiny(_ sender: UISwitch) {<br>        <br>        if sender.isOn == true {<br>            pokemonImageView.image = UIImage(named: pokemonShinyImageArray[num])<br>        } else{<br>            pokemonImageView.image = UIImage(named: pokemonImageArray[num])<br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*8IH7zpkxi9zEOJxALfGm5Q.gif" /><figcaption>切換異色寶可夢開關</figcaption></figure><blockquote>新增Page Control元件 小圓點換頁功能</blockquote><pre>@IBAction func changePageDot(_ sender: UIPageControl) {<br>        <br>        num = sender.currentPage<br>        switch sender.currentPage {<br>        case 0 :<br>            num = 0<br>            sync()<br>        case 1 :<br>            num = 1<br>            sync()<br>        case 2 :<br>            num = 2<br>            sync()<br>        case 3 :<br>            num = 3<br>            sync()<br>        case 4 :<br>            num = 4<br>            sync()<br>        default:<br>            num = 5<br>            sync()<br>        }<br>        <br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*-eFkj9A5KB423_RdlJl7gg.gif" /><figcaption>小圓點切換</figcaption></figure><blockquote>新增Segment元件 標籤換頁功能</blockquote><pre>    <br>    @IBAction func changeSegment(_ sender: UISegmentedControl) {<br>        <br>        num = sender.selectedSegmentIndex<br>        switch sender.selectedSegmentIndex {<br>        case 0 :<br>            num = 0<br>            sync()<br>        case 1 :<br>            num = 1<br>            sync()<br>        case 2 :<br>            num = 2<br>            sync()<br>        case 3 :<br>            num = 3<br>            sync()<br>        case 4 :<br>            num = 4<br>            sync()<br>        default:<br>            num = 5<br>            sync()<br>        }<br>        <br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*HfqpzPXQC1c5fnXBNRPEdg.gif" /><figcaption>標籤切換</figcaption></figure><blockquote>新增Button元件 左右按鈕換頁功能</blockquote><pre>//左箭頭換頁<br>    @IBAction func previousPage(_ sender: Any) {<br>        <br>        num -= 1<br>        switch num {<br>        case 0 :<br>            num = 0<br>            sync()<br>        case 1 :<br>            num = 1<br>            sync()<br>        case 2 :<br>            num = 2<br>            sync()<br>        case 3 :<br>            num = 3<br>            sync()<br>        case 4 :<br>            num = 4<br>            sync()<br>        default:<br>            num = 5<br>            sync()<br>        }<br>        <br>    }<br>    <br>    //右箭頭換頁<br>    @IBAction func nextPage(_ sender: Any) {<br>        num += 1<br>        switch num {<br>        case 0 :<br>            num = 0<br>            sync()<br>        case 1 :<br>            num = 1<br>            sync()<br>        case 2 :<br>            num = 2<br>            sync()<br>        case 3 :<br>            num = 3<br>            sync()<br>        case 4 :<br>            num = 4<br>            sync()<br>        case 5 :<br>            num = 5<br>            sync()<br>        default:<br>            num = 0<br>            sync()<br>        }<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*dnnRBx3_7d8hL4LPsOcnRg.gif" /><figcaption>左右箭頭切換按鈕</figcaption></figure><blockquote>啟用 Timer方法 ? 自動播放功能</blockquote><pre>var timer: Timer?<br>    @IBAction func autoPlay(_ sender: UIButton) {<br>        if sender.titleLabel?.text == &quot;自動播放&quot;{<br>            autoPlayButton.setTitle(&quot;停止&quot;, for: UIControl.State.normal)<br>            timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(startCarousell), userInfo: nil, repeats: true)<br>        } else {<br>            autoPlayButton.setTitle(&quot;自動播放&quot;, for: UIControl.State.normal)<br>   //停止Timer<br>            timer?.invalidate()<br>        }<br>        <br>    }<br>    <br>  //寫一個在 Timer觸發所要做的 objc func<br>    @objc func startCarousell() {<br>        num += 1<br>        if num == 6 {<br>            num = 0<br>            sync()<br>        } else {<br>            sync()<br>        }<br>        <br>    }</pre><p><strong>參數介紹：</strong></p><ul><li>timeInterval：觸發Timer的間隔時間，以秒為單位。</li><li>target：Timer 觸發的對象，self表示目前使用 UIViewController 本身。</li><li>selector：Timer 觸發後執行哪一個 objc func。</li><li>userInfo：可作為傳入Timer 觸發事件的資料，不使用傳入nil即可。</li><li>repeat：true啟用後會根據 timeInterval 時間間隔設定來重複觸發，若填入false則啟用後只觸發一次。</li></ul><blockquote><strong>停止使用 Timer 方法</strong></blockquote><p>當不使用 Timer 卻沒停止它的話，會一直在背景執行。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*ZqGLvUMbQsVbGgwvlfxJgg.gif" /><figcaption>自動播放功能</figcaption></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%E6%95%99%E5%AE%A4/11-ios-app-swift-timer-%E7%AD%86%E8%A8%98-%E5%AF%A6%E4%BD%9C-6a0c6d3aaf1b">#11 iOS App Swift Timer 筆記 &amp; 實作</a></p><blockquote>新增swipe gesture手勢換頁功能</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*NJ9yO9iCYF2kk3UQG7c8Ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*NKP5DcI0bA9Q99mm0oORXA.png" /><figcaption>兩個手勢功能連線同一個Action</figcaption></figure><p>點選滑動的View，勾選User Interaction Enabled</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*46PCFj3z5Rj6ok1Fm4FVhQ.png" /></figure><pre>//手勢換頁<br>    @IBAction func swipeChangePage(_ sender: UISwipeGestureRecognizer) {<br>        <br> //direction<br>        if  (sender.direction == .left) {<br>            <br>            num += 1<br>            switch num {<br>            case 0 :<br>                num = 0<br>                sync()<br>            case 1 :<br>                num = 1<br>                sync()<br>            case 2 :<br>                num = 2<br>                sync()<br>            case 3 :<br>                num = 3<br>                sync()<br>            case 4 :<br>                num = 4<br>                sync()<br>            default:<br>                num = 5<br>                sync()<br>            }<br>            <br>        } else if (sender.direction == .right) {<br>            <br>            num -= 1<br>            switch num {<br>            case 1 :<br>                num = 1<br>                sync()<br>            case 2 :<br>                num = 2<br>                sync()<br>            case 3 :<br>                num = 3<br>                sync()<br>            case 4 :<br>                num = 4<br>                sync()<br>            case 5 :<br>                num = 5<br>                sync()<br>            default:<br>                num = 0<br>                sync()<br>            }<br><br>        }<br>        <br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*dtEJYHBkbRSib4H0cuRdcA.gif" /><figcaption>左右滑動手勢操作</figcaption></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/%E9%96%8B%E7%99%BC-ios-app-%E7%9A%84-gesture-%E6%89%8B%E5%8B%A2%E5%8A%9F%E8%83%BD-uikit-%E7%89%88%E6%9C%AC-f6cb95075705">開發 iOS App 的 Gesture (手勢)功能 — UIKit 版本</a></p><blockquote>新增Long Press Gesture Recognizer長按手勢 隨機換頁功能</blockquote><pre>@IBAction func showRandomImage(_ sender: Any) {<br>        num = Int.random(in: 0...5)<br>        sync()<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*vrneqeEcIE0VuNnjYdtWyw.gif" /><figcaption>長按手勢隨機顯示</figcaption></figure><p><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/%E7%9C%9F%E6%84%9B%E7%9A%84%E6%A8%A1%E6%A8%A3-image-view-%E5%92%8C-segmented-control-%E7%B7%B4%E7%BF%92-675d64d5c94c">#38 利用 page control，segmented control，button &amp; gesture 更換內容</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=140c5a4a3f81" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/17-%E5%88%A9%E7%94%A8-page-control-segmented-control-button-gesture-%E6%9B%B4%E6%8F%9B%E5%85%A7%E5%AE%B9-140c5a4a3f81">#17 利用 page control，segmented control，button &amp; gesture 更換內容</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[#16 定義兩個類別， 用到繼承， 類別裡包含屬性和方法，在方法裡有使用到屬性，然後用類別生出物件 存取物件的屬性和呼叫物件的方法。]]></title>
            <link>https://medium.com/peter-pan-swift-ios-class/16-%E5%AE%9A%E7%BE%A9%E5%85%A9%E5%80%8B%E9%A1%9E%E5%88%A5-%E7%94%A8%E5%88%B0%E7%B9%BC%E6%89%BF-%E9%A1%9E%E5%88%A5%E8%A3%A1%E5%8C%85%E5%90%AB%E5%B1%AC%E6%80%A7%E5%92%8C%E6%96%B9%E6%B3%95-%E5%9C%A8%E6%96%B9%E6%B3%95%E8%A3%A1%E6%9C%89%E4%BD%BF%E7%94%A8%E5%88%B0%E5%B1%AC%E6%80%A7-%E7%84%B6%E5%BE%8C%E7%94%A8%E9%A1%9E%E5%88%A5%E7%94%9F%E5%87%BA%E7%89%A9%E4%BB%B6-%E5%AD%98%E5%8F%96%E7%89%A9%E4%BB%B6%E7%9A%84%E5%B1%AC%E6%80%A7%E5%92%8C%E5%91%BC%E5%8F%AB%E7%89%A9%E4%BB%B6%E7%9A%84%E6%96%B9%E6%B3%95-62331b5f451a?source=rss-ecffe12b9c07------2</link>
            <guid isPermaLink="false">https://medium.com/p/62331b5f451a</guid>
            <dc:creator><![CDATA[Lou]]></dc:creator>
            <pubDate>Sat, 04 Mar 2023 14:55:27 GMT</pubDate>
            <atom:updated>2023-03-10T03:05:39.554Z</atom:updated>
            <content:encoded><![CDATA[<p>用寶可夢Game Freak親兒子小火龍當作實例</p><pre>// 定義寶可夢類別<br>class Pokemon {<br>    var name = String()<br>    var hp = Double()<br>    var attack = Double()<br>    var defense = Double()<br>    var specialAttack = Double()<br>    var specialDefense = Double()<br>    var speed = Double()<br>    var terastal = String()<br>    var type = String()<br>    var type2 = String()<br>    <br>    //印出寶可夢基本資料<br>    func baseStats(){<br>        print(&quot;\(name) 屬性: \(type)&quot;)<br>        if (type2 != &quot;&quot;){<br>            print(&quot;\(name) 第二屬性: \(type2)&quot;)<br>        }<br>        print(&quot;\(name) 太晶化屬性: \(terastal)&quot;)<br>        print(&quot;\(name) 血量: \(hp)&quot;)<br>        print(&quot;\(name) 攻擊: \(attack)&quot;)<br>        print(&quot;\(name) 防禦: \(defense)&quot;)<br>        print(&quot;\(name) 特攻: \(specialAttack)&quot;)<br>        print(&quot;\(name) 特防: \(specialDefense)&quot;)<br>        print(&quot;\(name) 速度: \(speed)&quot;)<br>    }<br>    <br>    //得到噴射火焰技能<br>    func skillFlamethrower(){<br>        var power = 90.0<br>        if ((type == &quot;火&quot; || type2 == &quot;火&quot;) &amp;&amp; terastal == &quot;火&quot;) {<br>            power = power * 2<br>        } else if(type == &quot;火&quot; || type2 == &quot;火&quot;){<br>            power = power * 1.5<br>        } else if(terastal == &quot;火&quot;){<br>            power = power * 1.5<br>        }<br>        print(&quot;\(name) 使出了 噴射火焰 招式威力:\(power)&quot;)<br>    }<br>    <br>}<br><br>var charmander = Pokemon()<br>charmander.name = &quot;小火龍&quot;<br>charmander.type = &quot;火&quot;<br>charmander.terastal = &quot;火&quot;<br>charmander.hp = 39<br>charmander.attack = 52<br>charmander.defense = 43<br>charmander.specialAttack = 60<br>charmander.specialDefense = 50<br>charmander.speed = 65<br>charmander.baseStats()<br>charmander.skillFlamethrower()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*u2B36cNXX4TG3nlk1cbuwA.png" /><figcaption>捕捉到的小火龍</figcaption></figure><p>繼承寶可夢類別的極巨化類別</p><pre>//極巨化繼承寶可夢類別<br>class Dynamax: Pokemon {<br>    var dynamax = &quot;超極巨化&quot;<br>    <br>    //獲得超強極巨化招式<br>    func skillGMaxWildfire(){<br>        var power = 130.0<br>        if(type == &quot;火&quot; || type2 == &quot;火&quot;){<br>            power = power * 1.5<br>        }<br>        print(&quot;\(name)使用極巨腕帶 極巨化成為 \(dynamax+name)&quot;)<br>        print(&quot;\(dynamax+name) 使出了 超極巨地獄滅焰 招式威力:\(power)&quot;)<br>    }<br>}<br><br>var charizard = Dynamax()<br>charizard.name = &quot;噴火龍&quot;<br>charizard.type = &quot;火&quot;<br>charizard.type2 = &quot;飛行&quot;<br>charizard.terastal = &quot;火&quot;<br>charizard.hp = 78<br>charizard.attack = 84<br>charizard.defense = 78<br>charizard.specialAttack = 109<br>charizard.specialDefense = 85<br>charizard.speed = 100<br>charizard.baseStats()<br>charizard.skillFlamethrower()<br>charizard.skillGMaxWildfire()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*E4bKyxUWJpSlI1_lNdHpCw.png" /><figcaption>極巨化後的噴火龍</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62331b5f451a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/peter-pan-swift-ios-class/16-%E5%AE%9A%E7%BE%A9%E5%85%A9%E5%80%8B%E9%A1%9E%E5%88%A5-%E7%94%A8%E5%88%B0%E7%B9%BC%E6%89%BF-%E9%A1%9E%E5%88%A5%E8%A3%A1%E5%8C%85%E5%90%AB%E5%B1%AC%E6%80%A7%E5%92%8C%E6%96%B9%E6%B3%95-%E5%9C%A8%E6%96%B9%E6%B3%95%E8%A3%A1%E6%9C%89%E4%BD%BF%E7%94%A8%E5%88%B0%E5%B1%AC%E6%80%A7-%E7%84%B6%E5%BE%8C%E7%94%A8%E9%A1%9E%E5%88%A5%E7%94%9F%E5%87%BA%E7%89%A9%E4%BB%B6-%E5%AD%98%E5%8F%96%E7%89%A9%E4%BB%B6%E7%9A%84%E5%B1%AC%E6%80%A7%E5%92%8C%E5%91%BC%E5%8F%AB%E7%89%A9%E4%BB%B6%E7%9A%84%E6%96%B9%E6%B3%95-62331b5f451a">#16 定義兩個類別， 用到繼承， 類別裡包含屬性和方法，在方法裡有使用到屬性，然後用類別生出物件 存取物件的屬性和呼叫物件的方法。</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>