最後跟大家介紹一下鈴聲的頁面怎麼做
大部分的寫法其實和 repeatView 一樣
不過我們有用到新的套件喔!
我們首先需要用到一個叫 AVFoundation 的套件
import UIKit
import AVFoundation
@IBOutlet weak var tableView: UITableView!
weak var delegate: SoundViewControllerDelegate?
let sounds = ["馬林巴琴", "雷達", "警報", "豎琴"]
var selectedSoundIndex: Int = 0
var audioPlayer: AVAudioPlayer?
var currentSelectedSound: String?
一樣的我們需要去設定 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])
}
}
// 播放音效
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)")
}
}
接下來一樣的要設定 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])
}
}