0

I tried to use this solution but is not working. what I want i s a button in my customized cell that knows data from the array that is used from the tableview (later I'll apply it to CoreData), for example, print the value of the array that generated the tableview.

but I cannot understand how to do it

I have a customized cell class, where I tried to use both a button action or a outlet button (with tags):

import UIKit

class MyTableViewCell: UITableViewCell {


@IBOutlet weak var myCellImage: UIImageView!
@IBOutlet weak var myCellLabel: UILabel!

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
}





}

and a ViewController where is my tableview with an extension

extension ViewController {

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



func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    let cell = myTableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyTableViewCell

    cell.myCellLabel.text = String(indexPath.row)
    cell.myCellButton.tag = indexPath.row
    cell.myCellButton.addTarget(self, action: Selector("logAction:"), for: .touchUpInside)

    return cell
}


func logAction(sender: UIButton) {

    let titleString = self.comicsArray[sender.tag]

    let firstActivityItem = "\(titleString)"

    let activityVC = UIActivityViewController(activityItems: [firstActivityItem], applicationActivities: nil)

    self.present(activityVC, animated: true, completion: nil)

}



}

EDIT:

solved with help of abdullahselek by adding in subclasses cell:

public var dataFromTableView : String!

and implementing:

@IBAction func myCellButtonTapped(_ sender: UIButton) {


    guard dataFromTableView != nil else {return}

    print("pushed \(dataFromTableView!)")


}

and in cellForRowAt :

    cell.data = comicsArray[indexPath.row]
Community
  • 1
  • 1
biggreentree
  • 1,633
  • 3
  • 20
  • 35

1 Answers1

0

Add a dictionary or object model property to your custom tableviewcell like

public var data: Dictionary!

And set this data property

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    ...

    cell.data = comicsArray[indexPath.row]

}

Then you button can reach data with in your tableviewcell

abdullahselek
  • 7,893
  • 3
  • 50
  • 40