[英]Tap on button in table view and song will play in each of rows using swift
我有一個歌曲列表,應該通過點擊按鈕在表格視圖的每一行中播放。 我在自定義單元格中制作了一個按鈕和一個協議,用於在我們的視圖控制器中顯示點擊。 例如。 當我們點擊單元格中的第二個按鈕時,它應該播放第二首歌曲,當我們點擊第三個按鈕時,它應該播放第三首歌曲。
我的視圖控制器:
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)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.