0

I've already tried the indexPathForRowAtPoint solution and it initially worked and now I don't know what broke it. Does anyone have any advice as to what could be some common mistakes I might have made? Thanks.

    let pointInTable = sender.convertPoint(sender.bounds.origin, toView: self.tableView)
    let index = self.tableView.indexPathForRowAtPoint(pointInTable)?.row
    let prod_id = list[index].getProdID()
OOProg
  • 189
  • 1
  • 5
  • 16
  • 1
    Using indexPathForRowAtPoint is a good way to handle this. Post your code and we can help you debug it. – Duncan C Jul 25 '16 at 16:06
  • 1
    Possible duplicate of [detecting uibutton pressed in tableview: Swift Best Practices](http://stackoverflow.com/questions/27429652/detecting-uibutton-pressed-in-tableview-swift-best-practices) – Matt Le Fleur Jul 25 '16 at 16:07
  • I've posted my code...also I have the tag set and used for another purpose, so the sender.tag option won't be feasible. – OOProg Jul 25 '16 at 16:48

1 Answers1

0

I would create a custom cell that would have a closure callback, triggered by the button

import UIKit

class ButtonCell: UITableViewCell {

    @IBOutlet weak var button: UIButton! {
        didSet{
            button.addTarget(self, action: #selector(ButtonCell.buttonTapped(_:)), forControlEvents: .TouchUpInside)
        }
    }

    var buttonWasTapped: ((cell: ButtonCell) -> Void)?

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    func buttonTapped(sender:UIButton) {
        buttonWasTapped?(cell: self)
    }
}

Now in the datasource (note: here implemented in the view controller, better would be a separate datasource object) I set the callback to identify the cell, and with it I get the index path

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 30
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! ButtonCell
        cell.buttonWasTapped = {
            cell in
            let idxPath = tableView.indexPathForCell(cell)
            let alert = UIAlertController(title: "tapped", message: "cell at indexpath: \(idxPath)", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
        return cell
    }
}
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178