【问题标题】:How do I add a button in a table view cell that plays a different sound file on each row with swift如何在表格视图单元格中添加一个按钮,该按钮在每一行上快速播放不同的声音文件
【发布时间】:2015-10-01 12:52:56
【问题描述】:

我希望能够在UITableViewCell 中放置一个按钮,我可以在其中单击该按钮,它会在每一行播放不同的声音文件。实现这一目标的最佳代码是什么?

这是我的代码:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var mytableview: UITableView!
var arrayOfPersons: [Person] = [Person]()


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    self.setUpPersons()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func setUpPersons()
{
    let person1 = Person(name: "Anna\nAnna2\nAnna3", number: 60, imageName: "testingimage.jpg", soundButton: "dimsumgirl.mp3")
    let person2 = Person(name: "Joes", number: 10, imageName: "testingimage2.jpg", soundButton: "dimsumgirl.mp3")

    arrayOfPersons.append(person1)
    arrayOfPersons.append(person2)

}

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

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("Cell") as! CustomCell



    if indexPath.row % 2 == 0
    {
        cell.backgroundColor = UIColor.blackColor()
    }
    else
    {
        cell.backgroundColor = UIColor.blackColor()
    }

    let person = arrayOfPersons [indexPath.row]

    cell.setCell(person.name, rightlabelInt: person.number, imageName: person.imageName, soundButton: person.soundButton)



    return cell

我已经尝试使用上面的代码,但我似乎无法完全弄清楚如何将图片改为按钮并能够通过每个按钮播放声音。

非常感谢一些帮助!

谢谢!

【问题讨论】:

  • 你的代码有什么问题?你是什​​么意思图片按钮?
  • 嗨,T 先生,我想更改代码,而不是在行中显示图片,而是希望有一个按钮,在每行播放不同的声音文件。

标签: swift uitableview button audio


【解决方案1】:

在您的自定义单元格中,您应该有一个按钮并连接该单元格内的触摸事件。在 setCell 中,将按钮的背景图像设置为您传递的图像,并将类变量设置为您传入的声音文件。然后当触发 IBAction 触摸事件时,播放类变量中的声音。

【讨论】:

  • 嗨,耶利米,感谢您提供的信息。我对此有点陌生,我将如何设置类变量并能够为不同行上的不同按钮添加不同的声音文件?
  • 您在 CustomCell 中设置了一个类变量。该变量在每一行中都会有所不同。因此,例如在 setCell 内部:self.soundButton = soundButton。然后在按钮内单击播放(self.soundButton),无论需要什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多