繁体   English   中英

在Tableview单元格中快速处理播放/暂停按钮

[英]Swift handle Play/Pause button inTableview Cell

我试图在表格单元格中实现播放/暂停按钮。 每个单元格都有单个按钮,每当用户单击它时,都应更改按钮图像,还需要调用所需的功能,滚动后也应相同。

下面的代码我正在使用

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

    let cell = tableView.dequeueReusableCellWithIdentifier("productCell") as ? SepetCell
    cell.onButtonTapped = {
       //Do whatever you want to do when the button is tapped here
    }

首先,请查看tableView Cell的每个按钮将具有与之关联的唯一标签,因此,为了更新特定单元格的按钮,您将必须在单元格中定义按钮的标签,然后将此标签传递给您对选定单元格的特定按钮执行操作的功能。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
  {
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell_identifier", for: 
         indexPath) as! CellClass
      cell.button.tag  = indexPath.row
      cell.button.addTarget(self, action: #selector(playpause), for: .touchUpInside)
  }
  @objc func playpause(btn : UIButton){
       if btn.currentImage == UIImage(named: "Play") {
        btn.setImage(UIImage(named : "Pause"), forState: .Normal)
     }
      else {
        btn.setImage(UIImage(named : "Play"), forState: .Normal)
     }
   // perform your desired action of the button over here
  } 

Swift中最先进的技术是回调闭包。 它们易于实现且非常高效。

在数据源模型中添加一个属性

var isPlaying = false 

在Interface Builder中,选择自定义单元中的按钮,然后按⌥⌘4转到Attributes Inspector。 在弹出菜单“ State Config选择“ Default然后从“ Image弹出窗口中选择适当的图像,对“ Selected状态执行相同的操作。

在自定义单元格中,为该按钮添加一个回调属性以及一个插座和动作(将两者都连接到该按钮)。 通过isSelected属性设置图像。

@IBOutlet weak var button : UIButton!

var callback : (()->())?

@IBAction func push(_ sender: UIButton) {
    callback?()
} 

cellForRow的控制器中添加回调, item是数据源数组的当前项目。 按钮的状态保持在isPlaying

cell.button.isSelected = item.isPlaying
cell.callback = {
    item.isPlaying = !item.isPlaying
    cell.button.isSelected = item.isPlaying
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM