在swift中从另一个ViewController调用函数 [英] Calling function from another ViewController in swift
问题描述
我已经查看过Stackoverflow但我无法得到答案。我想创建停止在另一个ViewController中播放声音的函数。但是当我点击停止按钮时,它会破解并显示EXC_BAD_INSTRUCTION(code = EXC_I386_INVOP,subcode = 0x0)。这是我的代码。
I have already looked in Stackoverflow but I can't get an answer. I want to create function that stop playing the sound in another ViewController. But when I clicked the stop button, it cracked and showed "EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)". This is my code.
First ViewController
First ViewController
import UIKit
import AVFoundation
class FirstVC: UIViewController {
var metronome: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
do {
let resourcePath1 = Bundle.main.path(forResource: "music", ofType: "mp3")
let url = NSURL(fileURLWithPath: resourcePath1!)
try metronome = AVAudioPlayer(contentsOf: url as URL)
metronome.prepareToPlay()
metronome.play()
} catch let err as NSError {
print(err.debugDescription)
}
}
和另一个Viewcontroller是
and another Viewcontroller is
import UIKit
class SecondVC: UIViewController {
var metronomePlay = FirstVC()
@IBAction func stopBtnPressed(_ sender: Any) {
metronomePlay.metronome.stop() //"EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"
}
}
推荐答案
您正在创建FirstVC的新副本,并在尚未初始化的内容上调用stop。
You are creating a NEW copy of FirstVC and calling stop on something that is not yet initialised.
在这种情况下你真的应该使用委托,比如
You should really use a delegate in this case, something like
protocol controlsAudio {
func startAudio()
func stopAudio()
}
class FirstVC: UIViewController, controlsAudio {
func startAudio() {}
func stopAudio() {}
// later in the code when you present SecondVC
func displaySecondVC() {
let vc = SecondVC()
vc.delegate = self
self.present(vc, animated: true)
}
}
class SecondVC: UIViewController {
var delegate: controlsAudio?
// to start audio call self.delegate?.startAudio)
// to stop audio call self.delegate?.stopAudio)
}
所以你将第一个VC传递给第二个VC,所以当你调用这些函数时,你正在实际执行它正在使用的FirstVC,而不是创建一个新的。
So you are passing first VC to the second VC, so when you call these functions you are doing it on the actual FirstVC that is in use, rather than creating a new one.
如果您愿意,可以通过用<$ c $替换 var delegate:controlsAudio?
来执行此操作c> var firstVC:FirstVC?并指定它,但我不推荐它
You could do this without protocols if you like by replacing the var delegate: controlsAudio?
with var firstVC: FirstVC?
and assigning that, but I wouldn't recommend it
这篇关于在swift中从另一个ViewController调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!