sungwookbaek sungwookbaek - 29 days ago 20
Swift Question

How can I get indexPath.row in cell.swift

I have 2 files.


  • myTableViewController.swift

  • myTableCell.swift



Can I get the indexPath.row in myTabelCell.swift function?

Here is myTableCell.swift

import UIKit
import Parse
import ActiveLabel

class myTableCell : UITableViewCell {

//Button
@IBOutlet weak var commentBtn: UIButton!
@IBOutlet weak var likeBtn: UIButton!
@IBOutlet weak var moreBtn: UIButton!


override func awakeFromNib() {
super.awakeFromNib()


}

@IBAction func likeBtnTapped(_ sender: AnyObject) {

//declare title of button
let title = sender.title(for: UIControlState())

//I want get indexPath.row in here!

}


Here is myTableViewController.swift

class myTableViewController: UITableViewController {

//Default func
override func viewDidLoad() {
super.viewDidLoad()

//automatic row height
tableView.estimatedRowHeight = 450
tableView.rowHeight = UITableViewAutomaticDimension



}

// cell config
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


//define cell
let cell = tableView.dequeueReusableCell(withIdentifier: "myTableCell", for: indexPath) as! myTableCell



}


As you can see... I'm trying to get indexPath.row in myTableCell, liktBtnTapped function.

Could you let me know how can I access or get IndexPath.row?

Answer

A neat little extension that adds an indexPath property to a UITableViewCell.

import UIKit

extension UITableViewCell {

    var indexPath: IndexPath? {
        return (superview as? UITableView)?.indexPath(for: self)
    }
}

Here's an example of how you would use it:

@IBAction func likeBtnTapped(_ sender: AnyObject) {

    guard let indexPath = indexPath else { return }

    //declare title of button
    let title = sender.title(for: UIControlState())

    //I want get indexPath.row in here!
    print(indexPath)
}
Comments