如何在我的設置中製作「激活/關閉背景音樂」按鈕?Swift:根據遊戲狀態,如何製作UISwitch按鈕作爲設置?
音樂只在遊戲啓動時播放。 (點擊「開始」播放 - >背景音樂也播放。)
我已經編碼了這一刻,但我真的不知道該怎麼做。
class SettingsViewController: UITableViewController {
// MARK: - IBOutlets
@IBOutlet weak var backgroundgMusicLabel: UILabel!
@IBOutlet weak var backgroundMusicSwitch: UISwitch!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func backgroundMusicPressed(_ sender: Any) {
if backgroundMusicSwitch.isOn {
UserDefaults().set("On", forKey: "switch")
} else {
UserDefaults().set("Off", forKey: "switch")
}
}
}
雖然我有這個代碼在我MainViewController:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if game == .ready {
start()
}
}
和我一起玩音樂是這樣的:
var audioPlayer: AVAudioPlayer?
func playMusic() {
let url = Bundle.main.url(forResource: "MyMusic", withExtension: "mp3")!
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
guard let audioPlayer = audioPlayer else { return }
audioPlayer.prepareToPlay()
audioPlayer.play()
} catch let error {
print(error.localizedDescription)
}
}