我开发了一个抽认卡应用程序,我有一个 UIImageView 以及用于更改图片的手势点击和一个用于根据图像播放声音的按钮。
这是正在发生的事情,我使用一个数字循环遍历所有图像:
// if the tapped view is a UIImageView then set it to imageview
if (gesture.view as? UIImageView) != nil {
if segControl.selectedSegmentIndex == 0 && segControl2.selectedSegmentIndex == 0 {
imageView.image = UIImage(named: "card2")
imageView.image = UIImage(named: "card\(number)")
number = number % 26 + 1
}
else if segControl.selectedSegmentIndex == 0 && segControl2.selectedSegmentIndex == 1 {
imageView.image = UIImage(named: "upper2")
imageView.image = UIImage(named: "upper\(number)")
number = number % 26 + 1
}
else if segControl.selectedSegmentIndex == 0 && segControl2.selectedSegmentIndex == 2 {
imageView.image = UIImage(named: "num2")
imageView.image = UIImage(named: "num\(number)")
number = number % 10 + 1
}
}
然后我有一个按钮应该根据 ImageView 中显示的图像播放声音:
if imageView.image == UIImage(named: "card1") {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: aSound))
audioPlayer.play()
} catch {
print("Couldn't load sound file")
}
}
else if imageView.image != UIImage(named: "card2") {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: bSound))
audioPlayer.play()
} catch {
print("Couldn't load sound file")
}
}
else if imageView.image != UIImage(named: "card3") {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: cSound))
audioPlayer.play()
} catch {
print("Couldn't load sound file")
}
}
}
我已经为声音设置了所有变量并将它们添加为对我的 xcode 项目的引用:
var audioPlayer = AVAudioPlayer()
let aSound = Bundle.main.path(forResource: "aSound.m4a", ofType:nil)!
let bSound = Bundle.main.path(forResource: "bSound.m4a", ofType:nil)!
let cSound = Bundle.main.path(forResource: "cSound.m4a", ofType:nil)!
问题是当我按下声音按钮时,它每次都播放相同的声音,就好像它从未读过我的 if 语句。
最佳答案
问题在于,当您尝试以这种方式比较图像时
if imageView.image == UIImage(named: "card1") {
...
}
您实际上是在尝试比较两个具有不同引用的不同对象。
为了实现您想要的行为,您可以采用两种不同的解决方案。
第一个是使用 View 的tag
属性:
if segControl.selectedSegmentIndex == 0 && segControl2.selectedSegmentIndex == 0 {
imageView.image = UIImage(named: "card2")
imageView.image = UIImage(named: "card\(number)")
// HERE YOU CAN ADD A TAG
imageView.tag = 1 //for example, it has to be Int
number = number % 26 + 1
}
所以你用这种方式比较标签
:
if imageView.tag == 1 {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: aSound))
audioPlayer.play()
} catch {
print("Couldn't load sound file")
}
}
等等。
第二个是使用isEqual
,它应该比较对象的hash
值:
if imageView.image.isEqual(UIImage(named: "")){
...
}
关于swift - 基于 UIImageVIew 命名图像播放声音不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56817637/