How can I get indexPath.row in cell.swift
I have created a UIResponder
extension with a recursive method that you can use in any UIView
(which inherits from UIResponder
) to find a parent view of a specific type.
import UIKitextension UIResponder { /** * Returns the next responder in the responder chain cast to the given type, or * if nil, recurses the chain until the next responder is nil or castable. */ func next<U: UIResponder>(of type: U.Type = U.self) -> U? { return self.next.flatMap({ $0 as? U ?? $0.next() }) }}
Using this, we can extend UITableViewCell
with some convenient read-only computed properties for the table view and index path of the cell.
extension UITableViewCell { var tableView: UITableView? { return self.next(of: UITableView.self) } var indexPath: IndexPath? { return self.tableView?.indexPath(for: self) }}
Here is how you could use it in your example:
@IBAction func likeBtnTapped(_ sender: AnyObject) { //declare title of button let title = sender.title(for: UIControlState()) //I want get indexPath.row in here! self.indexPath.flatMap { print($0) }}
Swift 4+
Try this inside your cell.
func getIndexPath() -> IndexPath? { guard let superView = self.superview as? UITableView else { print("superview is not a UITableView - getIndexPath") return nil } indexPath = superView.indexPath(for: self) return indexPath}
Easy.. You can do like this inside button action:
let section = 0let row = sender.taglet indexPath = IndexPath(row: row, section: section)let cell: myTableCell = self.feedTableView.cellForRow(at: indexPath) as! myTableCell
And afterwards in cellForRowAtIndexPath
:
// add the row as the tagcell.button.tag = indexPath.row