gpt4 book ai didi

ios - Swift:在与 View 匹配的tapGestureRecognizer中播放声音

转载 作者:行者123 更新时间:2023-11-29 05:46:33 25 4
gpt4 key购买 nike

在 forEach 方法中,我得到了一组 View (一个 View 是一张带有动物图像的卡片)。这是一个卡片组 View ,当向左或向右滑动时,会显示下一张卡片。所以我想在 UITapgestureRecognize 中播放与 View 匹配的声音。

动物库存:

class AnimalsStock {

var list = [Animal]()
init() {

let item = Animal(name: "Bear", soundUrl: "Bear", imageName: "Bear")

list.append(item)

list.append(Animal(name: "Cat", soundUrl: "Cat", imageName: "Cat"))
list.append(Animal(name: "Chicken", soundUrl: "Chicken", imageName: "Chicken"))
list.append(Animal(name: "Cow", soundUrl: "Cow", imageName: "Cow"))
}
}

主视图 Controller

HomeController: UIViewController {
func setupCards() {

allAnimals.list.forEach { (animal) in
let cardView = CardView(frame: .zero)
cardView.imageView.image = UIImage(named: animal.imageName)
cardView.animalLabel.text = animal.name
cardDeckView.addSubview(cardView)
cardView.fillSuperview()
}

}
}

并使用 UITapgestureRecognizer 文件

 class CardView: UIView {

@objc fileprivate func tapCard(recognizer: UITapGestureRecognizer) {
// Here, I would like to implement a method that plays a sound that matches to the image
pulseCard()

}
}

播放声音方法:

var player : AVAudioPlayer?

func playSound(soundUrl: String) {
guard let url = Bundle.main.url(forResource: soundUrl, withExtension: "mp3") else { return }
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)

player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }

player.play()
} catch let error {
print(error.localizedDescription)
}
}
func stopSound() {
if player != nil {
player?.stop()
}

}

提前致谢

最佳答案

您可以在 for-each 循环中为每个 CardView 分配一个唯一的标记,方法是使其枚举项目,然后使用该标记/索引访问您的动物列表以获取网址。

或者,您始终可以使 CardView 具有 Animal 属性并分配该属性,因此 CardView 只需读出动物即可已分配。

关于ios - Swift:在与 View 匹配的tapGestureRecognizer中播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099281/

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