如何在 cell.swift 中获得 indexPath.row

How can I get indexPath.row in cell.swift

我有 2 个文件。

我可以在 myTabelCell.swift 函数中获取 indexPath.row 吗?

这里是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!

    }

这里是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



 }

如您所见...我正在尝试在 myTableCell、liktBtnTapped 函数中获取 indexPath.row。

你能告诉我如何访问或获取 IndexPath.row 吗?

简单..你可以在按钮操作中这样做:

let section = 0
let row = sender.tag
let indexPath = IndexPath(row: row, section: section)
let cell: myTableCell = self.feedTableView.cellForRow(at: indexPath) as! myTableCell

之后 cellForRowAtIndexPath

// add the row as the tag
cell.button.tag = indexPath.row

在单元格class中创建一个属性indexPath,并在单元格重复使用时在cellForRowAtIndexPath中设置。

但有一个警告:一些 table 重新排列单元格的视图方法不会调用 cellForRowAtIndexPath。你必须考虑这种情况。

但是,如果您始终只使用 reloadData(),它既安全又简单。


另一种方法是将有关 controlling 事情的代码放回 controller class 和 运行它通过回调闭包捕获索引路径。

我创建了一个带有递归方法的 UIResponder 扩展,您可以在任何 UIView(继承自 UIResponder)中使用它来查找特定类型的父视图。

import UIKit

extension 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({ [=10=] as? U ?? [=10=].next() })
    }
}

使用它,我们可以使用一些方便的只读计算属性来扩展 UITableViewCell table 单元格的视图和索引路径。

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

    var indexPath: IndexPath? {
        return self.tableView?.indexPath(for: self)
    }
}

以下是您如何在示例中使用它:

@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([=12=]) }
}

这是另一种方法

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()


}


}


class myTableViewController: UITableViewController {

//Default func
//assuming you have an array for your table data source
var arrayOfTitles = [String]()
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
cell.commentBtn.tag = indexPath.row
cell.commentBtn.addTarget(self, action: #selector(likeBtnTapped(_:), forControlEvents:.TouchUpInside)


//cell config end


@IBAction func likeBtnTapped(sender: UIButton) {
let btn = sender
let indexP = NSIndexPath(forItem: btn.tag, inSection: 0)
let cell = tableView.dequeueReusableCell(withIdentifier: "myTableCell", for: indexP) as! myTableCell

    //I want get indexPath.row in here!
    let title = arrayOfTitles[indexP.row]

    //declare title of button
    cell.commentBtn.setTitle(title, forState: UIControlState.Normal)



}


}

我的解决方案是子class UITableViewCell,因此可以添加 IndexPath 属性。为故事板中的 table 视图单元分配自定义 class。在调用 rowAtIndexPath 时分配 IndexPath 值。

class MyTableViewCell: UITableViewCell {

    var indexPath: IndexPath?
}

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

    var cell = tableView.dequeueReusableCell(withIdentifier: "cellid1", for: indexPath)
    (cell as? MyTableViewCell)?.indexPath = indexPath
    return cell
}

Swift 4+

在你的牢房里试试这个。

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
}

Swift 4.1。在这里,我创建了获取 IndexPath 的函数。只需传递您的 UIView(UIButton、UITextField 等)和 UITableView 对象即可获取 IndexPath。

func getIndexPathFor(view: UIView, tableView: UITableView) -> IndexPath? {

            let point = tableView.convert(view.bounds.origin, from: view)
            let indexPath = tableView.indexPathForRow(at: point)
            return indexPath
 }

Swift 4.2 的另一种方法,不假设 Superview 将始终是 tableview

extension UITableViewCell{

    var tableView:UITableView?{
        return superview as? UITableView
    }

    var indexPath:IndexPath?{
        return tableView?.indexPath(for: self)
    }

}

使用示例

@IBAction func checkBoxAction(_ sender: UIButton) {

        guard let indexPath = indexPath else { return }

        sender.isSelected = !sender.isSelected
        myCustomCellDelegate?.checkBoxTableViewCell(didSelectCheckBox: sender.isSelected, for: indexPath)

}

Swift 5:

        if 
            let collectionView = superview as? UICollectionView, 
            let index = collectionView.indexPath(for: self) 
        {
            // stuff
        }