Swift 如何在进入屏幕时自动播放音频
我正在学习Swift,我正在通过构建一个应用程序强迫自己学习这门语言而陷入困境。我想实现的是,当我从屏幕1转移到屏幕2时,不需要做任何事情就可以播放音频。音频是A-14a。下面的代码设置为,当我单击“方向”按钮时,它会播放音频,但我不知道如何立即播放。下面的图片有助于说明我的意思 我的代码如下:Swift 如何在进入屏幕时自动播放音频,swift,xcode,audio,autoplay,Swift,Xcode,Audio,Autoplay,我正在学习Swift,我正在通过构建一个应用程序强迫自己学习这门语言而陷入困境。我想实现的是,当我从屏幕1转移到屏幕2时,不需要做任何事情就可以播放音频。音频是A-14a。下面的代码设置为,当我单击“方向”按钮时,它会播放音频,但我不知道如何立即播放。下面的图片有助于说明我的意思 我的代码如下: 导入UIKit 进口AVF基金会 类干预\u数字1:UIViewController{ @IBVAR方向:UIButton! @IBVAR完成:UIButton! var audioPlayer=A
导入UIKit
进口AVF基金会
类干预\u数字1:UIViewController{
@IBVAR方向:UIButton!
@IBVAR完成:UIButton!
var audioPlayer=AVAudioPlayer()
重写func viewDidLoad(){
super.viewDidLoad()
setUpElements()
//音频测试
做{
audioPlayer=尝试AVAudioPlayer(内容:URL.init(fileURLWithPath:Bundle.main.path(用于资源:“A-N14a”,类型:“mp3”)!)
audioPlayer.prepareToPlay()
}抓住{
打印(错误)
}
}
func setUpElements(){
//为元素设置样式
实用程序.样式填充按钮(方向)
Utilities.StyleFilled按钮(完成)
}
@iAction func播放(\发送方:任意){
audioPlayer.play()
}
}
使用此方法
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
audioPlayer.play()
}
有两种方法可以重写以了解视图控制器的状态,并添加代码以在该状态发生时运行 正如阿米拉所提到的,您正在寻找的可能是
viewdide
,
另一种可能也有助于实现这一点的方法是viewwillbeen
我将在下面提供大多数方法的代码以及它们的作用,以便您可以尝试所有方法并进行实验:
override func viewDidLoad() {
//This is what you already use every time, its called when the VC's view is loaded into memory
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//This happens when the view is *about* to appear, it happens before users see anything from the view, great for updating UI
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//This happens when the view actually appears on screen and when all the animations of loading the View Controller are over.
//not so good for updating UI since users will see a glimpse of previous view data.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//This happens when the view is *about* to disappear, great example for this is when you begin swiping to go back in a navigation controller.
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
//This happens when view is no longer on screen for user to see, like when that swiping back animation in using navigation controller is *finished*
}
当视图控制器中的视图发生更改时,还会出现其他一些视图,如viewWillLayoutSubviews
和viewdillayoutsubviews
使用所有这些来控制什么时候发生,希望这有帮助:)