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

问题描述 投票:21回答:9

我有2个文件。

  • myTableViewController.swift
  • myTableCell.swift

我可以在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吗?

swift uitableview nsindexpath
9个回答
30
投票

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

import UIKit

extension UIResponder {

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

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

extension UITableViewCell {

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

    var indexPath: IndexPath? {
        return 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!
    indexPath.flatMap { print($0) }
}

11
投票

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
}

3
投票

容易..您可以在按钮操作中执行此操作:

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

2
投票

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
 }

1
投票

在单元格类中创建属性indexPath,并在重用单元格时将其设置在cellForRowAtIndexPath中。

但有一点需要注意:重新排列单元格的一些表格视图方法不会调用cellForRowAtIndexPath。你必须考虑这种情况。

但如果你总是只使用reloadData()它是安全的,非常容易。


另一种方法是将有关控制事物的代码放回控制器类中,并通过捕获索引路径的回调闭包来运行它。


1
投票

这是另一种做法

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)



}


}

1
投票

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

class MyTableViewCell: UITableViewCell {

    var indexPath: IndexPath?
}

custom class

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

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

1
投票

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)

}

0
投票

斯威夫特5:

        if 
            let collectionView = superview as? UICollectionView, 
            let index = collectionView.indexPath(for: self) 
        {
            // stuff
        }
© www.soinside.com 2019 - 2024. All rights reserved.