gpt4 book ai didi

ios - Swift:如何根据游戏状态将 UISwitch 按钮设置为设置?

转载 作者:可可西里 更新时间:2023-11-01 01:23:13 27 4
gpt4 key购买 nike

如何在我的设置中制作“激活/停用背景音乐”按钮?

音乐仅在游戏启动时播放。 (点击“开始”播放 -> 背景音乐也播放。)

我暂时已经编写了这个代码,但我真的不知道该怎么做。

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")
}
}
}

我的 SettingsViewController

当我的 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)
}
}

最佳答案

TheValyreanGroup Globals 是正确的。

class Globals: NSObject {
static let sharedInstance = Globals()
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)
}
}
}

但在您的情况下,请尝试以下代码:

主视图 Controller :

static let sharedInstance = Globals()
let globalVars = Globals.sharedInstance

并在您的start() 函数中添加此函数:

func checkMusicStatus() {
let status = UserDefaults().string(forKey: "switch")
if status == "Off"{
if (self.globalVars.audioPlayer?.isPlaying != nil){
self.globalVars.audioPlayer?.stop()
}
} else {
self.globalVars.playMusic()
}
}

它应该有效,希望这会有所帮助。

关于ios - Swift:如何根据游戏状态将 UISwitch 按钮设置为设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42696757/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com