点击表格视图中的按钮,歌曲将使用swift在每一行播放



我有一个歌曲列表,应该通过点击按钮在表视图的每一行中播放。我在自定义单元格中制作了一个按钮和一个协议,用于在我们的视图控制器中显示点击。例如,当我们点击单元格中的第二个按钮时,它应该播放第二首歌,当我们按下第三个按钮时它播放第三首歌。

我的ViewController:

import UIKit
import AVFoundation
class BeatPackViewController: UIViewController {

@IBOutlet weak var beatTableView: UITableView!
@IBOutlet weak var coverImage: UIImageView!
@IBOutlet weak var looppackNameLabel: UILabel!
@IBOutlet weak var producerNameLabel: UILabel!
@IBOutlet weak var backButtonLabel: UIButton!
let data = DataLoader().beatData
var songs: [String] = []

var audioPlayer = AVAudioPlayer()

func getSongs() -> [String] {
var names: [String] = []
let path = Bundle.main.resourceURL?.appendingPathComponent("songs")
do {
let songs = try FileManager.default.contentsOfDirectory(at: path!, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)

for song in songs {
let strArray = song.absoluteString.components(separatedBy: "/")
var songName = strArray[strArray.count - 1].replacingOccurrences(of: "%20", with: " ")
songName = songName.replacingOccurrences(of: ".wav", with: "")
names.append(songName)
}
} catch {}

return names
}

func playSong(index: Int) {
do {
let songPath = Bundle.main.path(forResource: songs[index], ofType: ".wav", inDirectory: "songs")
try audioPlayer = AVAudioPlayer(contentsOf: URL(fileURLWithPath: songPath!))
audioPlayer.play()
} catch {}
}

override func viewDidLoad() {
super.viewDidLoad()

beatTableView.delegate = self
beatTableView.dataSource = self

self.view.backgroundColor = SettingsService.sharedService.backgroundColor
coverImage.layer.cornerRadius = 20
coverImage.layer.shadowRadius = 7
coverImage.layer.shadowOpacity = 0.8
coverImage.layer.shadowOffset = CGSize(width: 3, height: 3)
coverImage.layer.shadowColor = UIColor.black.cgColor
coverImage.clipsToBounds = true
}

}

extension BeatPackViewController: UITableViewDataSource, UITableViewDelegate {

func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = beatTableView.dequeueReusableCell(withIdentifier: "firstLoopCell", for: indexPath as IndexPath) as! CustomLoopsCell
cell.loopNameLabel.text = data[indexPath.row].loop_name
cell.delegate = self
cell.playButtonOutlet.addTarget(self, action: #selector(CustomLoopsCell.playButtonPressed(_:)), for: .touchUpInside)
//        cell.instrumentLabel.text = data[indexPath.row].loops[indexPath.row].Instrument
//        cell.producerLabel.text = data[indexPath.row].loops[indexPath.row].producer
return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
didTapButton()
}

}
extension BeatPackViewController: CustomLoopsDelegate {
func didTapButton() {
}

}

我的自定义单元格

import UIKit
import AVFoundation
protocol CustomLoopsDelegate: AnyObject {
func didTapButton()
}
class CustomLoopsCell: UITableViewCell {

weak var delegate: CustomLoopsDelegate?

var songs: [String] = []

var audioPlayer = AVAudioPlayer()


@IBOutlet weak var loopNameLabel: UILabel!
@IBOutlet weak var producerLabel: UILabel!
@IBOutlet weak var instrumentLabel: UILabel!
@IBOutlet weak var playButtonOutlet: UIButton!

override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

// Configure the view for the selected state
}

@IBAction func playButtonPressed(_ sender: UIButton) {
delegate?.didTapButton()
}
}
正如Paulw11所说,不要在cellForRowAt中使用btn操作,您需要添加delegate。检查我试过的关于你的代码。这里你不需要didSelect方法

BeatPackViewController.Swift

class BeatPackViewController: UIViewController, CustomLoopsDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : CustomLoopsCell = tableView.dequeueReusableCell(withIdentifier: "firstLoopCell", for: indexPath) as! CustomLoopsCell
cell.delegate = self
return cell
}

func btnUseTap(cell: CustomLoopsCell) {
let indexPath = self.tableview.indexPath(for: cell)
//play song here
}
}

CustomLoopsCell.Swift

protocol CustomLoopsDelegate: AnyObject {
func btnUseTap(cell: CustomLoopsCell)
}
class CustomLoopsCell: UITableViewCell {

weak var delegate: CustomLoopsDelegate?

override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}

@IBAction func btnUse(_ sender: Any) {
delegate?.btnUseTap(cell: self)
}

}

更新歌曲播放代码

let audioData = try! Data(contentsOf: url, options: .mappedIfSafe)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try! AVAudioSession.sharedInstance().setActive(true)
do {
self.audioPlayer = try AVAudioPlayer(data: audioData, fileTypeHint: AVFileType.m4a.rawValue)
self.audioPlayer.prepareToPlay()
self.audioPlayer.play()
if isVideoMute {
self.audioPlayer.volume = 0
}else {
self.audioPlayer.volume = 1
}
} catch let error {
print(error.localizedDescription)
}

最新更新