iT邦幫忙

2025 iThome 鐵人賽

DAY 26
0
Mobile Development

我將點燃Swiftの大海系列 第 26

Day26. Swift一定要會のios鬧鐘復刻實作篇 (7)

  • 分享至 

  • xImage
  •  

(進階) SoundView

最後跟大家介紹一下鈴聲的頁面怎麼做
大部分的寫法其實和 repeatView 一樣
不過我們有用到新的套件喔!

import

我們首先需要用到一個叫 AVFoundation 的套件

import UIKit
import AVFoundation

IBOutlet

    @IBOutlet weak var tableView: UITableView!

變數

    weak var delegate: SoundViewControllerDelegate?
    let sounds = ["馬林巴琴", "雷達", "警報", "豎琴"]
    var selectedSoundIndex: Int = 0
    var audioPlayer: AVAudioPlayer?
    var currentSelectedSound: String?

LifeCycle

一樣的我們需要去設定 if 條件式去設定鈴聲,記得包進去 ViewDidLoad 中

        // 設定初始選擇的音效
        if let currentSound = currentSelectedSound,
           let index = sounds.firstIndex(of: currentSound) {
                    selectedSoundIndex = index
                }

與重複頁面同樣要設定移除畫面自動儲存!

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if self.isMovingFromParent {
            delegate?.didSelectSound(sounds[selectedSoundIndex])
        }
    }

Functions

    // 播放音效
    func playSound(named name: String) {
        guard let url = Bundle.main.url(forResource: name, withExtension: "mp3") else { return }
        
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.play()
        } catch {
            print("無法播放音效: \(error.localizedDescription)")
        }
    }

extension

接下來一樣的要設定 tableView
最後設定 protocol !
別忘記要設定好跟昨天新增頁面設定時一樣的檔案命名規則喔
不然會找不到鈴聲檔案!

extension SoundViewController: UITableViewDelegate, UITableViewDataSource {
    // 設定 tableView 的行數
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sounds.count
    }
    // 設定每個 cell 的內容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SoundTableViewCell", for: indexPath) as! SoundTableViewCell
        cell.lbTest.text = sounds[indexPath.row]
        cell.accessoryType = indexPath.row == selectedSoundIndex ? .checkmark : .none
        return cell
    }
    
    // 設定 cell 的高度
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedSoundIndex = indexPath.row
        tableView.reloadData()
        playSound(named: sounds[indexPath.row])
    }
}

上一篇
Day25. Swift一定要會のios鬧鐘復刻實作篇 (6)
下一篇
Day27. Swift一定要會の天氣API實作篇 (1)
系列文
我將點燃Swiftの大海30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言