我将 Imageview 添加到视图后,声音立即停止播放。视图是持有者。如果我删除设置 Imageview 的属性和约束的代码,声音确实会播放。我唯一的猜测是我搞砸了约束......?最后一个方法,名为 configureUI(),是我尝试设置图像视图并为其提供约束的地方。顾名思义,这个图像视图是将要播放的当前歌曲的封面图像。
在此先感谢那些提供帮助的人。
import UIKit
import AVFoundation
class PLayerViewController: UIViewController {
@IBOutlet var holder: UIView!
var gabayArray = [Gabays]()
var position: Int = 0
var player: AVAudioPlayer?
//user interface elements
var coverImageView: UIImageView!
var gabayName: UILabel!
var gabyaaName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
configurePlayer()
configureUI()
}
override func viewWillAppear(_ animated: Bool) {
if let player = player {
player.stop()
}
print("yo")
}
override func viewDidLayoutSubviews() {
if holder.subviews.count == 0 {
configure()
}
print("yooo")
}
func configurePlayer() {
//set up player
let gabay = gabayArray[position]
let urlString = Bundle.main.path(forResource: gabay.gabayName, ofType: "mp3")
do {
try AVAudioSession.sharedInstance().setMode(.default)
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
guard let urlString = urlString else{return}
player = try AVAudioPlayer(contentsOf: URL(string: urlString)!)
guard let player = player else{return}
player.play()
print("zip it")
}
catch{
print("error is: \(error.localizedDescription)")
}
}
func configureUI() {
//set up user interface
let gabay = gabayArray[position]
coverImageView = UIImageView()
coverImageView.backgroundColor = .systemBlue
coverImageView.image = UIImage(named: gabay.imageName)
holder.addSubview(coverImageView)
gabayName = UILabel()
gabyaaName = UILabel()
//set up constraints
NSLayoutConstraint.activate([
coverImageView.topAnchor.constraint(equalTo: holder.layoutMarginsGuide.topAnchor, constant: 20),
coverImageView.leadingAnchor.constraint(equalTo: holder.layoutMarginsGuide.leadingAnchor, constant: 10),
coverImageView.trailingAnchor.constraint(equalTo: holder.layoutMarginsGuide.trailingAnchor, constant: -10),
coverImageView.widthAnchor.constraint(equalTo: holder.widthAnchor, multiplier: 0.8),
coverImageView.heightAnchor.constraint(equalTo: holder.heightAnchor, multiplier: 0.5)
])
}
}
重构这些部分
1- 将
translatesAutoresizingMaskIntoConstraints
设置为 imageView
coverImageView.translatesAutoresizingMaskIntoConstraints = false
2-删除这些代码
override func viewDidLayoutSubviews() {
if holder.subviews.count == 0 {
configure()
}
print("yooo")
}
&
override func viewWillAppear(_ animated: Bool) {
if let player = player {
player.stop()
}
print("yo")
}