F. Bar F. Bar - 1 month ago 11
Swift Question

Get index path for table cell

I currently have a tableview with multiple cells each containing a button.

I'm trying to simply print out cell number when the button of that cell has been clicked. To achieve this I have tried using a CGPoint and then getting the index from that, but every time I run in the simulator, i'm getting error:


*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIBarButtonItem
convertPoint:toView:]: unrecognized selector sent to instance
0x7ff61c505780'





I have connected my button to an IBOutlet Action which I have written:

@IBAction func upVote(_ sender: AnyObject) {
let btnPos: CGPoint = sender.convert(CGPoint.zero, to: self.tableView)
let indexPath: NSIndexPath = self.tableView.indexPathForRow(at: btnPos)! as NSIndexPath
print(indexPath.row)
}


Unsure how to tackle this, any help would be appreciated.

Thanks

EDIT: FIX

@IBAction func upVote(_ sender: AnyObject) {
let btnPos: CGPoint = sender.convert(CGPoint.zero, to: self.tableView)
let indexPath = self.tableView.indexPathForRow(at: btnPos)!
let rowToAction = indexPath.first!
print(rowToAction)
}

Answer

Another way to get indexpath it's a cell delegate.

//Create the protocol
@objc protocol MusicCellDelegate {
     func didPressListenButton(button:UIButton, cell: MusicCell)
}

 class MusicCell: UITableViewCell {
        // set the delate prop to cell
        var delegate: MusicCellDelegate?

        // in your button action
       @IBAction func didPressPlayButton(sender: UIButton) {
        self.delegate?.didPressListenButton(button: sender, cell: self)
       }
    }

    // in controller
extension MusicController: UITableViewDataSource {
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            guard let cell = tableView.dequeueReusableCell(withIdentifier: MusicCell.reuseIdentifier(), for: indexPath) as? MusicCell else {
                fatalError("Can't deque cell Music Cell")
            }
            cell.delegate = self

            return cell
        }
}

extension MusicController: MusicCellDelegate {

    func didPressListenButton(button:UIButton, cell: MusicCell) {
        let indexPath = musicTable.indexPath(for:cell)
    }
}
Comments