119

I have a tableview with buttons and I want to use the indexpath.row when one of them is tapped. This is what I currently have, but it always is 0

var point = Int()
func buttonPressed(sender: AnyObject) {
    let pointInTable: CGPoint =         sender.convertPoint(sender.bounds.origin, toView: self.tableView)
    let cellIndexPath = self.tableView.indexPathForRowAtPoint(pointInTable)
    println(cellIndexPath)
    point = cellIndexPath!.row
    println(point)
}
Vincent
  • 1,645
  • 3
  • 14
  • 22
  • should I use IndexPathForSelectedRow() instead of the point variable? or where should I use it? – Vincent Feb 22 '15 at 16:58

20 Answers20

176

giorashc almost had it with his answer, but he overlooked the fact that cell's have an extra contentView layer. Thus, we have to go one layer deeper:

guard let cell = sender.superview?.superview as? YourCellClassHere else {
    return // or fatalError() or whatever
}

let indexPath = itemTable.indexPath(for: cell)

This is because within the view hierarchy a tableView has cells as subviews which subsequently have their own 'content views' this is why you must get the superview of this content view to get the cell itself. As a result of this, if your button is contained in a subview rather than directly into the cell's content view, you'll have to go however many layers deeper to access it.

The above is one such approach, but not necessarily the best approach. Whilst it is functional, it assumes details about a UITableViewCell that Apple have never necessarily documented, such as it's view hierarchy. This could be changed in the future, and the above code may well behave unpredictably as a result.

As a result of the above, for longevity and reliability reasons, I recommend adopting another approach. There are many alternatives listed in this thread, and I encourage you to read down, but my personal favourite is as follows:

Hold a property of a closure on your cell class, have the button's action method invoke this.

class MyCell: UITableViewCell {
    var button: UIButton!

    var buttonAction: ((Any) -> Void)?

    @objc func buttonPressed(sender: Any) {
        self.buttonAction?(sender)
    }
}

Then, when you create your cell in cellForRowAtIndexPath, you can assign a value to your closure.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! MyCell
    cell.buttonAction = { sender in
        // Do whatever you want from your button here.
    }
    // OR
    cell.buttonAction = buttonPressed(closure: buttonAction, indexPath: indexPath) // <- Method on the view controller to handle button presses.
}

By moving your handler code here, you can take advantage of the already present indexPath argument. This is a much safer approach that the one listed above as it doesn't rely on undocumented traits.

Jacob King
  • 6,025
  • 4
  • 27
  • 45
  • Deleted my answer as it's the same with yours. I suggest an edit to the answer above without the ugly `if let` statements to `let cell = view.superview.superview as! ` – jaytrixz Dec 29 '15 at 02:04
  • The if let statements are there to prevent the app from crashing should any of the superviews be nil, this is the correct way to unwrap and should not be considered 'ugly'. – Jacob King Dec 29 '15 at 22:25
  • itemTable is the name of my previously declared UITableView – Jacob King Jan 29 '16 at 09:13
  • indexPathForCell will return type of NSIndexPath. so the var indexPath should not be Int! it should be var indexPath: NSIndexPath! – Swayambhu Jul 21 '16 at 08:27
  • 2
    Well spotted. I am a competent developer, I promise ;) - Have amended my answer. – Jacob King Jul 22 '16 at 09:18
  • 15
    This is not the proper way to get the cell from a button. A cell's layout has changed over the years and code like this will fail to work when that happens. Do not use this approach. – rmaddy Feb 03 '17 at 18:15
  • 12
    This is a bad solution. It assumes details about UITableViewCells that Apple has never necessarily agreed to. While UITableViewCells have a contentView property there is no guarantee that the contentView's superview will always be the Cell. – bpapa Feb 04 '17 at 12:47
  • @bpapa I did make a point of saying this in the answer, it's not like I didn't make the OP aware... – Jacob King Feb 06 '17 at 07:09
  • if let cell = sender.superview?.superview as? UITableViewCell { } is not working for me. – Pintu Rajput Nov 08 '17 at 08:07
  • 1
    @PintuRajput Can you describe your view hierarchy to me please? You're likely seeing this because your button is not a direct subview of the cell's content view. – Jacob King Nov 08 '17 at 10:08
  • @JacobKing Done :( – Pintu Rajput Nov 08 '17 at 10:13
  • This solution also assumes the button pressed isn't nested within any other views. – Erick Maynard Feb 13 '18 at 02:42
  • Traversing superviews is a very bad idea. – CW0007007 May 09 '18 at 12:52
  • This answer is like a joke. You should not use superview to reach parent views. This could break with any minor update in view hierarchy – ymutlu Aug 07 '18 at 07:44
  • 2
    @ymutlu I totally agree, I did state this in the answer. I also proposed a much more robust solution. The reason I left the original in place is because I feel it's better to show other devs the issues with an approach than dodge it altogether, this teaches them nothing you see. :) – Jacob King Aug 08 '18 at 00:10
69

My approach to this sort of problem is to use a delegate protocol between the cell and the tableview. This allows you to keep the button handler in the cell subclass, which enables you to assign the touch up action handler to the prototype cell in Interface Builder, while still keeping the button handler logic in the view controller.

It also avoids the potentially fragile approach of navigating the view hierarchy or the use of the tag property, which has issues when cells indexes change (as a result of insertion, deletion or reordering)

CellSubclass.swift

protocol CellSubclassDelegate: class {
    func buttonTapped(cell: CellSubclass)
}

class CellSubclass: UITableViewCell {

@IBOutlet var someButton: UIButton!

weak var delegate: CellSubclassDelegate?

override func prepareForReuse() {
    super.prepareForReuse()
    self.delegate = nil
}

@IBAction func someButtonTapped(sender: UIButton) {
    self.delegate?.buttonTapped(self)
}

ViewController.swift

class MyViewController: UIViewController, CellSubclassDelegate {

    @IBOutlet var tableview: UITableView!

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

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CellSubclass

        cell.delegate = self

        // Other cell setup

    } 

    //  MARK: CellSubclassDelegate

    func buttonTapped(cell: CellSubclass) {
        guard let indexPath = self.tableView.indexPathForCell(cell) else {
            // Note, this shouldn't happen - how did the user tap on a button that wasn't on screen?
            return
        }

        //  Do whatever you need to do with the indexPath

        print("Button tapped on row \(indexPath.row)")
    }
} 
Paulw11
  • 108,386
  • 14
  • 159
  • 186
  • `buttonTapped` is the delegate function and is in the view controller. In my example, `someButtonTapped` is the action method in the cell – Paulw11 Oct 24 '16 at 07:09
  • @paulw11 I got cell has no member buttonTapped in this method `@IBAction func someButtonTapped(sender: UIButton) { self.delegate?.buttonTapped(self) }` – Bhavin Bhadani Oct 24 '16 at 07:19
  • Your cell shouldn't be it's own delegate. The view controller is the delegate – Paulw11 Oct 24 '16 at 07:22
  • Check your code - it should say `weak var delegate: FollowingCellDelegate?` not `weak var delegate: FollowingCell? = nil` Also since the delegate is optional there is no need to explicitly assign `nil` – Paulw11 Oct 24 '16 at 07:35
  • 1
    This is a pretty good solution (nowhere near as bad as the two currently with more votes, using the tag looking at the superview) but it feels like too much extra code to be adding. – bpapa Feb 04 '17 at 12:52
  • 4
    This is the correct solution and should be the accepted answer. It does not abuse the tag property, does not assume the construction of cells (that can easily be changed by Apple) and will still work (with no extra coding) when cells are moved or new cells added in between existing cells. – Robotic Cat Feb 04 '17 at 13:03
  • @bpapa there isn't too much extra code here. You would need to write code to handle the tap anyway, so the "extra" code is 3 lines of protocol definition, 1 line for the delegate property, 1 to set it, 1 to clear it and 1 to invoke it, however I do like the closure answer too. – Paulw11 Feb 04 '17 at 13:33
  • Protocol, delegate, complexity, etc. I've always used the "locate the button in the scroll view" method described, 2 lines. – bpapa Feb 04 '17 at 14:29
  • 1
    @Paulw11 I initially thought this was a lot of code, but it's proven a lot more resilient than what I was using before. Thank you for posting this robust solution. – Adrian May 18 '17 at 18:02
  • This is the best solution I have found so far! Thank you so much! – Karishma Jul 13 '17 at 11:04
  • This is the correct solution and should be the accepted answer. – ymutlu Aug 07 '18 at 07:42
  • This is a good clean solution but it requires a lot of setup. I prefer my solution of adding an extension to UITableView. (See my answer.) – Duncan C Jan 27 '19 at 12:52
  • i think delegate property should be weak otherwise it create retain Cycle. – Bhavesh.iosDev Feb 06 '19 at 05:30
  • Good answer! Best for me – Wangdu Lin Aug 05 '19 at 18:32
  • Nice Solution just Change : `swift tableView.indexPathForCell(cell) ` for `swift tableView.indexPath(for: cell) ` – finalpets Nov 28 '19 at 19:59
60

UPDATE: Getting the indexPath of the cell containing the button (both section and row):

Using Button Position

Inside of your buttonTapped method, you can grab the button's position, convert it to a coordinate in the tableView, then get the indexPath of the row at that coordinate.

func buttonTapped(_ sender:AnyObject) {
    let buttonPosition:CGPoint = sender.convert(CGPoint.zero, to:self.tableView)
    let indexPath = self.tableView.indexPathForRow(at: buttonPosition)
}

NOTE: Sometimes you can run into an edge case when using the function view.convert(CGPointZero, to:self.tableView) results in finding nil for a row at a point, even though there is a tableView cell there. To fix this, try passing a real coordinate that is slightly offset from the origin, such as:

let buttonPosition:CGPoint = sender.convert(CGPoint.init(x: 5.0, y: 5.0), to:self.tableView)

Previous Answer: Using Tag Property (only returns row)

Rather than climbing into the superview trees to grab a pointer to the cell that holds the UIButton, there is a safer, more repeatable technique utilizing the button.tag property mentioned by Antonio above, described in this answer, and shown below:

In cellForRowAtIndexPath: you set the tag property:

button.tag = indexPath.row
button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

Then, in the buttonClicked: function, you reference that tag to grab the row of the indexPath where the button is located:

func buttonClicked(sender:UIButton) {
    let buttonRow = sender.tag
}

I prefer this method since I've found that swinging in the superview trees can be a risky way to design an app. Also, for objective-C I've used this technique in the past and have been happy with the result.

Hardik Thakkar
  • 15,269
  • 2
  • 94
  • 81
Iron John Bonney
  • 2,451
  • 1
  • 17
  • 14
  • 6
    This is a nice way of doing it, and I will upvote it to get your rep started a bit, however the only flaw is it doesn't give access to the indexPath.section if this is also needed. Great answer though! – Jacob King Apr 16 '16 at 11:22
  • Thanks Jacob! I appreciate the rep karma. If you wanted to get the `indexPath.section` in addition to the `indexPath.row` (without resetting the tag property as `indexPath.section`), in `cellForRowAtIndexPath:` you could just change the tag to `button.tag = indexPath`, and then in the `buttonClicked:` function you could access both by using `sender.tag.row` and `sender.tag.section`. – Iron John Bonney Apr 27 '16 at 00:17
  • 1
    Is this a new feature, because I'm sure I remember the tag property being of type Int not type AnyObject, unless that changed in swift 2.3? – Jacob King Apr 27 '16 at 17:33
  • @JacobKing you're right! My bad I totally spaced when writing that comment and was thinking that tag was type AnyObject. Derp - don't mind me. It would be useful if you could pass the indexPath as a tag though... – Iron John Bonney Apr 27 '16 at 18:26
  • hum this is embarrassing because i spent a lot of time trying to figure it out, but it might be useful for some people : "button" is an @IBOutlet UIButton that has to be created in the TableViewCell. And finally and in cellForRowAtIndexPath : cell?.button.tag = indexPath.row cell?.button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside) – Matthew Usdin Jun 26 '16 at 21:04
  • 3
    Not really a good approach either. For one thing, it would only work in Table Views where there is a single section. – bpapa Feb 04 '17 at 12:49
  • @bpapa That's correct, using the tag property only returns the row, so it only works for a single section. I just updated the answer to provide a way to grab the indexPath, so that you can use it with a multi-section tableView. – Iron John Bonney Feb 09 '17 at 17:36
  • You can easily store the section and the row/item in one Integer. See my answer... – mramosch Oct 17 '20 at 01:18
21

Use an extension to UITableView to fetch the cell that contains any view:


@Paulw11's answer of setting up a custom cell type with a delegate property that sends messages to the table view is a good way to go, but it requires a certain amount of work to set up.

I think walking the table view cell's view hierarchy looking for the cell is a bad idea. It is fragile - if you later enclose your button in a view for layout purposes, that code is likely to break.

Using view tags is also fragile. You have to remember to set up the tags when you create the cell, and if you use that approach in a view controller that uses view tags for another purpose you can have duplicate tag numbers and your code can fail to work as expected.

I have created an extension to UITableView that lets you get the indexPath for any view that is contained in a table view cell. It returns an Optional that will be nil if the view passed in actually does not fall within a table view cell. Below is the extension source file in it's entirety. You can simply put this file in your project and then use the included indexPathForView(_:) method to find the indexPath that contains any view.

//
//  UITableView+indexPathForView.swift
//  TableViewExtension
//
//  Created by Duncan Champney on 12/23/16.
//  Copyright © 2016-2017 Duncan Champney.
//  May be used freely in for any purpose as long as this 
//  copyright notice is included.

import UIKit

public extension UITableView {
  
  /**
  This method returns the indexPath of the cell that contains the specified view
   
   - Parameter view: The view to find.
   
   - Returns: The indexPath of the cell containing the view, or nil if it can't be found
   
  */
  
    func indexPathForView(_ view: UIView) -> IndexPath? {
        let center = view.center
        let viewCenter = self.convert(center, from: view.superview)
        let indexPath = self.indexPathForRow(at: viewCenter)
        return indexPath
    }
}

To use it, you can simply call the method in the IBAction for a button that's contained in a cell:

func buttonTapped(_ button: UIButton) {
  if let indexPath = self.tableView.indexPathForView(button) {
    print("Button tapped at indexPath \(indexPath)")
  }
  else {
    print("Button indexPath not found")
  }
}

(Note that the indexPathForView(_:) function will only work if the view object it's passed is contained by a cell that's currently on-screen. That's reasonable, since a view that is not on-screen doesn't actually belong to a specific indexPath; it's likely to be assigned to a different indexPath when it's containing cell is recycled.)

EDIT:

You can download a working demo project that uses the above extension from Github: TableViewExtension.git

Duncan C
  • 128,072
  • 22
  • 173
  • 272
11

Solution:

You have a button (myButton) or any other view in cell. Assign tag in cellForRowAt like this

cell.myButton.tag = indexPath.row

Now in you tapFunction or any other. Fetch it out like this and save it in a local variable.

currentCellNumber = (sender.view?.tag)!

After this you can use anywhere this currentCellNumber to get the indexPath.row of selected button.

Enjoy!

Sajid Zeb
  • 1,806
  • 18
  • 32
  • That approach works, but view tags are fragile, as mentioned in my answer. A simple integer tag won't work for a sectioned table view, for example. (an IndexPath it 2 integers.) My approach will always work, and there's no need to install a tag into the button (or other tappable view.) – Duncan C Jan 26 '20 at 04:14
  • You can easily store the section and the row/item in one Integer. See my answer... – mramosch Oct 17 '20 at 01:14
9

For Swift2.1

I found a way to do it, hopefully, it'll help.

let point = tableView.convertPoint(CGPoint.zero, fromView: sender)

    guard let indexPath = tableView.indexPathForRowAtPoint(point) else {
        fatalError("can't find point in tableView")
    }
funclosure
  • 498
  • 6
  • 15
  • What does it mean if the error runs? What are some reasons why it can't find the point in the tableView? – OOProg Jul 25 '16 at 16:38
  • This (or similar, using the UIView Converting methods) should be the accepted answer. Not sure why it's currently #4, as it doesn't make assumptions about a table view's private heirarchy, it doesn't use the tag property (almost always a bad idea), and doesn't involve a lot of extra code. – bpapa Feb 04 '17 at 12:55
7

In Swift 4 , just use this:

func buttonTapped(_ sender: UIButton) {
        let buttonPostion = sender.convert(sender.bounds.origin, to: tableView)

        if let indexPath = tableView.indexPathForRow(at: buttonPostion) {
            let rowIndex =  indexPath.row
        }
}
Thomas
  • 1,445
  • 14
  • 30
DEEPAK KUMAR
  • 341
  • 4
  • 8
4

Very Simple getting Index Path swift 4, 5

let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! Cell
cell.btn.tag = indexPath.row
cell.btn.addTarget(self, action: "buttonTapped:", forControlEvents: 
UIControlEvents.TouchUpInside)

How to get IndexPath Inside Btn Click :

func buttonTapped(_ sender: UIButton) {
     print(sender.tag)  
}
Birju Vachhani
  • 6,072
  • 4
  • 21
  • 43
M Murteza
  • 1,629
  • 15
  • 10
3

Since the sender of the event handler is the button itself, I'd use the button's tag property to store the index, initialized in cellForRowAtIndexPath.

But with a little more work I'd do in a completely different way. If you are using a custom cell, this is how I would approach the problem:

  • add an 'indexPath` property to the custom table cell
  • initialize it in cellForRowAtIndexPath
  • move the tap handler from the view controller to the cell implementation
  • use the delegation pattern to notify the view controller about the tap event, passing the index path
Antonio
  • 71,651
  • 11
  • 148
  • 165
  • Antonio, I have a custom cell and would love to do this your way. However, it is not working. I want my 'swipe to reveal delete button' code to run, which is the tableView commitEditingStyle method. I removed that code from the mainVC class and put it in the customCell class, but now the code no longer works. What am I missing? – Dave G Aug 18 '15 at 08:18
  • I think this is the best way to get the indexPath of a cell with x sections, however I don't see the need for bullet points 3 and 4 in a MVC approach – Edward Apr 26 '17 at 12:16
2

After seeing Paulw11's suggestion of using a delegate callback, I wanted to elaborate on it slightly/put forward another, similar suggestion. Should you not want to use the delegate pattern you can utilise closures in swift as follows:

Your cell class:

class Cell: UITableViewCell {
    @IBOutlet var button: UIButton!

    var buttonAction: ((sender: AnyObject) -> Void)?

    @IBAction func buttonPressed(sender: AnyObject) {
        self.buttonAction?(sender)
    }
}

Your cellForRowAtIndexPath method:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! Cell
    cell.buttonAction = { (sender) in
        // Do whatever you want from your button here.
    }
    // OR
    cell.buttonAction = buttonPressed // <- Method on the view controller to handle button presses.
}
Jacob King
  • 6,025
  • 4
  • 27
  • 45
2

Swift 4 and 5

Method 1 using Protocol delegate

For example, you have a UITableViewCell with name MyCell

class MyCell: UITableViewCell {
    
    var delegate:MyCellDelegate!
    
    @IBAction private func myAction(_ sender: UIButton){
        delegate.didPressButton(cell: self)
    }
}

Now create a protocol

protocol MyCellDelegate {
    func didPressButton(cell: UITableViewCell)
}

Next step, create an Extension of UITableView

extension UITableView {
    func returnIndexPath(cell: UITableViewCell) -> IndexPath?{
        guard let indexPath = self.indexPath(for: cell) else {
            return nil
        }
        return indexPath
    }
}

In your UIViewController implement the protocol MyCellDelegate

class ViewController: UIViewController, MyCellDelegate {
     
    func didPressButton(cell: UITableViewCell) {
        if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
              print(indexpath)
        }
    }
}

Method 2 using closures

In UIViewController

override func viewDidLoad() {
        super.viewDidLoad()
       //using the same `UITableView extension` get the IndexPath here
        didPressButton = { cell in
            if let indexpath = self.myTableView.returnIndexPath(cell: cell) {
                  print(indexpath)
            }
        }
    }
 var didPressButton: ((UITableViewCell) -> Void)

class MyCell: UITableViewCell {

    @IBAction private func myAction(_ sender: UIButton){
        didPressButton(self)
    }
}

Note:- if you want to get UICollectionView indexPath you can use this UICollectionView extension and repeat the above steps

extension UICollectionView {
    func returnIndexPath(cell: UICollectionViewCell) -> IndexPath?{
        guard let indexPath = self.indexPath(for: cell) else {
            return nil
        }
        return indexPath
    }
}
Rashid Latif
  • 2,809
  • 22
  • 26
1

I used convertPoint method to get point from tableview and pass this point to indexPathForRowAtPoint method to get indexPath

 @IBAction func newsButtonAction(sender: UIButton) {
        let buttonPosition = sender.convertPoint(CGPointZero, toView: self.newsTableView)
        let indexPath = self.newsTableView.indexPathForRowAtPoint(buttonPosition)
        if indexPath != nil {
            if indexPath?.row == 1{
                self.performSegueWithIdentifier("alertViewController", sender: self);
            }   
        }
    }
Avijit Nagare
  • 8,482
  • 7
  • 39
  • 68
1

Try using #selector to call the IBaction.In the cellforrowatindexpath

            cell.editButton.tag = indexPath.row
        cell.editButton.addTarget(self, action: #selector(editButtonPressed), for: .touchUpInside)

This way you can access the indexpath inside the method editButtonPressed

func editButtonPressed(_ sender: UIButton) {

print(sender.tag)//this value will be same as indexpath.row

}
Vineeth Krishnan
  • 432
  • 2
  • 9
  • 20
1

Seems I'm a little late to the party, but I have brought some interesting piece of code.

How to handle button taps in a cell

To handle button taps in a UITableViewCell or its subclasses I would definitely suggest delegation pattern which is covered above to have some Separation of Concerns for both the cell and the viewController.

How to find indexPath of a cell

However, if for some other reasons you need to find the indexPath of a cell when a button or any other UIView subclass inside it is tapped I would suggest using class extensions. This way you could achieve Interface Segregation and SOLIDify your code a little bit.

Problem with other solutions:

  • Tags: as suggested above they are fragile when you insert or delete a row

  • Using superView property: It is not neat by any means. How many layers of views should you pass to reach the cell itself or the containing tableView. You may end up having something like this in your code which is not beautiful :

        let tableView = view.superView.superView.superView.superView
    

What I suggest:

First

Create an extension on UIResponder to get the first superView of a view of type T in the view hierarchy.

extension UIResponder {
    func next<T: UIResponder>(_ type: T.Type) -> T? {
        self.next as? T ?? self.next?.next(type)
    }
}   

This will iterate the whole view hierarchy until it finds a view of the given type or the end of the hierarchy in which it will return nil.

Next

Write an extension on UITableViewCell and use the next method to find the tableView to which the cell belongs and the indexPath of the cell.

extension UITableViewCell {
    var tableView: UITableView? {
        return next(UITableView.self)
    }

    var indexPath: IndexPath? {
        return tableView?.indexPathForRow(at: self.center)
        //return tableView?.indexPath(for: self) // Note: This will return nil if the cell is not visible yet
    }
}  

That's it. Neat and simple.

Use it wherever you want like this.

func buttonTapped(_ sender: UIButton) {
    guard let cell = sender.next(YourCellType.self), let indexPath = cell.indexPath else {
        return
    }
    
    // Use indexPath here
}
Mehdi Ijadnazar
  • 4,532
  • 4
  • 35
  • 35
0

In Swift 3. Also used guard statements, avoiding a long chain of braces.

func buttonTapped(sender: UIButton) {
    guard let cellInAction = sender.superview as? UITableViewCell else { return }
    guard let indexPath = tableView?.indexPath(for: cellInAction) else { return }

    print(indexPath)
}
Sean
  • 59
  • 2
  • This will not work. The button's superview will not be the cell. – rmaddy Feb 03 '17 at 18:16
  • This does work. The only thing you should be carefully of is that everyone's view stack is different. It could be sender.superview, sender.superview.superview or sender.superview.superview.superview. But it works really well. – Sean Feb 10 '17 at 17:17
0

Sometimes button may be inside of another view of UITableViewCell. In that case superview.superview may not give the cell object and hence the indexPath will be nil.

In that case we should keep finding the superview until we get the cell object.

Function to get cell object by superview

func getCellForView(view:UIView) -> UITableViewCell?
{
    var superView = view.superview

    while superView != nil
    {
        if superView is UITableViewCell
        {
            return superView as? UITableViewCell
        }
        else
        {
            superView = superView?.superview
        }
    }

    return nil
}

Now we can get indexPath on button tap as below

@IBAction func tapButton(_ sender: UIButton)
{
    let cell = getCellForView(view: sender)
    let indexPath = myTabelView.indexPath(for: cell)
}
Teena nath Paul
  • 2,219
  • 23
  • 28
0

In my case i have multiple sections and both the section and row index is vital, so in such a case i just created a property on UIButton which i set the cell indexPath like so:

fileprivate struct AssociatedKeys {
    static var index = 0
}

extension UIButton {

    var indexPath: IndexPath? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKeys.index) as? IndexPath
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.index, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

Then set the property in cellForRowAt like this :

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! Cell
    cell.button.indexPath = indexPath
}

Then in the handleTapAction you can get the indexPath like this :

@objc func handleTapAction(_ sender: UIButton) {
    self.selectedIndex = sender.indexPath

}
DvixExtract
  • 1,275
  • 15
  • 25
0
// CustomCell.swift

protocol CustomCellDelegate {
    func tapDeleteButton(at cell: CustomCell)
}

class CustomCell: UICollectionViewCell {
    
    var delegate: CustomCellDelegate?
    
    fileprivate let deleteButton: UIButton = {
        let button = UIButton(frame: .zero)
        button.setImage(UIImage(named: "delete"), for: .normal)
        button.addTarget(self, action: #selector(deleteButtonTapped(_:)), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        return button
    }()
    
    @objc fileprivate func deleteButtonTapped(_sender: UIButton) {
        delegate?.tapDeleteButton(at: self)
    }
    
}

//  ViewController.swift

extension ViewController: UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as? CustomCell else {
            fatalError("Unexpected cell instead of CustomCell")
        }
        cell.delegate = self
        return cell
    }

}

extension ViewController: CustomCellDelegate {

    func tapDeleteButton(at cell: CustomCell) {
        // Here we get the indexPath of the cell what we tapped on.
        let indexPath = collectionView.indexPath(for: cell)
    }

}
iAleksandr
  • 595
  • 10
  • 11
0

Extend UITableView to create function that get indexpath for a view:

extension UITableView {
    func indexPath(for view: UIView) -> IndexPath? {
        self.indexPathForRow(at: view.convert(.zero, to: self))
    }
}

How to use:

let row = tableView.indexPath(for: sender)?.row
jqgsninimo
  • 6,562
  • 1
  • 36
  • 30
-1

USING A SINGLE TAG FOR ROWS AND SECTIONS

There is a simple way to use tags for transmitting the row/item AND the section of a TableView/CollectionView at the same time.

Encode the IndexPath for your UIView.tag in cellForRowAtIndexPath :

buttonForCell.tag = convertIndexPathToTag(with: indexPath)

Decode the IndexPath from your sender in your target selector:

    @IBAction func touchUpInsideButton(sender: UIButton, forEvent event: UIEvent) {

        var indexPathForButton = convertTagToIndexPath(from: sender)

    }

Encoder and Decoder:

func convertIndexPathToTag(indexPath: IndexPath) -> Int {
    var tag: Int = indexPath.row + (1_000_000 * indexPath.section)
    
    return tag
}

func convertTagToIndexPath(from sender: UIButton) -> IndexPath {
    var section: Int = Int((Float(sender.tag) / 1_000_000).rounded(.down))
    var row: Int = sender.tag - (1_000_000 * section)

    return IndexPath(row: row, section: section)
}

Provided that you don’t need more than 4294967296 rows/items on a 32bit device ;-) e.g.

  • 42949 sections with 100_000 items/rows
  • 4294 sections with 1_000_000 items/rows - (like in the example above)
  • 429 sections with 10_000_000 items/rows

—-

WARNING: Keep in mind that when deleting or inserting rows/items in your TableView/CollectionView you have to reload all rows/items after your insertion/deletion point in order to keep the tag numbers of your buttons in sync with your model.

—-

mramosch
  • 458
  • 4
  • 14