user10222734
user10222734

Reputation:

Swift handle Play/Pause button inTableview Cell

I am trying to implement play/pause button in tableview cell. each cell having single button, whenever user click it, It should change button image also need to call required function, also after scroll it should same.

Below code I am using

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
    }

Upvotes: 0

Views: 891

Answers (2)

vadian
vadian

Reputation: 285150

State of the art in Swift are callback closures. They are easy to implement and very efficient.

In the data source model add a property

var isPlaying = false 

In Interface Builder select the button in the custom cell and press ⌥⌘4 to go to the Attributes Inspector. In the popup menu State Config select Default and choose the appropriate image from Image popup, Do the same for the Selected state.

In the custom cell add a callback property and an outlet and action for the button (connect both to the button). The image is set via the isSelected property.

@IBOutlet weak var button : UIButton!

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

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

In the controller in cellForRow add the callback, item is the current item of the data source array. The state of the button is kept in isPlaying

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

Upvotes: 1

Samarth Kejriwal
Samarth Kejriwal

Reputation: 1176

See first of all every button of the tableView Cell will have a unique tag associated with it, so in order to update the button of a particular cell, you will have to define the tag of a button in the cells and then pass this tag to your function to perform action on that particular button of the selected 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
  } 

Upvotes: 2

Related Questions