Я постараюсь объяснить это как можно лучше.
Я создаю приложение Sound Board. Все программно без StoryBoard. Приложение использует UICollectionView для размещения всех имен кавычек в ячейках. Цитаты также являются кнопками. Каждая ячейка представляет собой кнопку, которая должна соответствовать определенному звуковому файлу WAV.
Я использую звуки звездных войн в качестве теста для приложения - может быть проще, если я опубликую большую часть своего кода.
Я хотел бы назначить тестовый звук "blaster-firing"
для имени ячейки "Test Name"
и звук "yodalaughing"
для имени ячейки "Test Name 2"
У меня есть работающий код и ячейки; Когда вы нажимаете на названия ячеек, он воспроизводит только звук бластера, я знаю, это потому, что у меня есть только 1 кнопка-тег, установленная на button1, эта button1 выполняется для каждой ячейки.
Можно ли создавать разные теги кнопок для связи с созданными мной цитатами? Я не уверен, что лучший способ сделать это.
Вот мой ViewController:
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellId = "cellId"
//add different quotes for cells
let quotes = [Quote(name:"Test Name"),
Quote(name: "Test Name2")]
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = UIColor.darkGray
navigationItem.title = "Board"
navigationController?.navigationBar.barTintColor = UIColor(red: 0/255, green: 200/255, blue: 255/255, alpha: 1)
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 20)]
collectionView?.register(SoundBoardCell.self, forCellWithReuseIdentifier: cellId)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return quotes.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! SoundBoardCell
cell.quote = quotes[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (view.frame.width / 1) - 16, height: 100)
}
private func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insertForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
}
У меня также есть другой класс под названием SoundBoardCells
class SoundBoardCell: UICollectionViewCell, AVAudioPlayerDelegate {
//let testSoundFiles = ["baster-fire", "yodalaughing"]
var audio1 = AVAudioPlayer()
var audio2 = AVAudioPlayer()
var quote: Quote? {
didSet {
guard let quoteName = quote?.name else {return}
button1.setTitle("\(quoteName)", for: .normal)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
setCellShadow()
}
func setCellShadow() {
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 1)
self.layer.shadowOpacity = 1
self.layer.shadowRadius = 1.0
self.layer.masksToBounds = false
self.clipsToBounds = false
self.layer.cornerRadius = 3
}
func setup() {
self.backgroundColor = UIColor.lightGray
self.addSubview(button1)
do {
let audioPlayer1 = Bundle.main.path(forResource: "blaster-firing", ofType: "wav")
try audio1 = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPlayer1!))
} catch {
//ERROR
}
do {
let audioPlayer2 = Bundle.main.path(forResource: "yodalaughing", ofType: "wav")
try audio2 = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPlayer2!))
} catch {
}
// button setups
button1.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0)
button1.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside)
}
// button creations
let button1: UIButton = {
let button = UIButton()
button.tag = 0
button.layer.cornerRadius = 5
button.layer.borderColor = UIColor.black.cgColor
button.layer.borderWidth = 1
button.setTitle("", for: .normal)
button.setTitleColor(.cyan, for: .normal)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.frame = CGRect(x: 50, y: 50, width: 150, height: 150)
return button
}()
@IBAction func buttonClicked(sender: UIButton!) {
// print(quote!.name! as Any)
if (sender.tag == 0) {
audio1.play()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
struct Quote {
let name: String?
}