获取单元格中的 indexPath.row



当我点击我的按钮时,我尝试在单元格中获取 indexPath.row:

@IBAction func cellPlayButtonPressed(_ sender: Any) {
let cell = (sender as AnyObject).superview??.superview as? UITableViewCell
let indexPath = runnerTableView.indexPath(for: cell!)
print(indexPath)
}

当我按下按钮时,我遇到此错误:

致命错误:解开可选值时意外发现 nil

我已经尝试了在堆栈溢出上找到的所有内容,但没有任何效果。

让我知道错误在哪里!谢谢:)

只需复制给定的扩展名

extension UITableView {    
func indexPath(forItem: AnyObject) -> IndexPath? {
let itemPosition: CGPoint = forItem.convert(CGPoint.zero, to: self)
return self.indexPathForRow(at: itemPosition)
}}

用:

@IBAction func cellPlayButtonPressed(_ sender: Any) {
if let indexPath = runnerTableView.indexPath(forItem: sender) {
print(indexPath)
}
}

试试这段代码:

@IBAction func cellPlayButtonPressed(_ sender: Any) {
guard let button = sender as? UIButton else { return }
let indexPath = tableView.indexPathForRow(at: button.center)
print(indexPath)
}

我已经创建了演示并测试了它作为方面的工作方式。您可以按如下方式使用:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
let fruitName = fruits[indexPath.row]
cell.textLabel?.text = fruitName
cell.detailTextLabel?.text = "Delicious!"
cell.imageView?.image = UIImage(named: fruitName)
//Button added for click event
let btn = UIButton.init(frame: CGRect(x: 10, y: 10, width: 100, height: 30))
btn.backgroundColor = UIColor.red
btn.setTitle("Click Here", for: UIControlState.normal)
btn.addTarget(self, action: #selector(clickMe), for: .touchUpInside)
cell.addSubview(btn)
return cell
}
func clickMe(sender : UIButton){
let indexpath : NSIndexPath =  self.indexPathForCellContainingView(view: sender, inTableView: self.tableView)
print("Current IndexPath Row : (indexpath.row) Column : (indexpath.section)")
}
func indexPathForCellContainingView(view: UIView, inTableView tableView: UITableView) -> NSIndexPath {
let viewCenterRelativeToTableview = tableView.convert(CGPoint(x: view.bounds.midX, y: view.bounds.midY), from: view)
let cellIndexPath = tableView.indexPathForRow(at: viewCenterRelativeToTableview)!
return cellIndexPath as NSIndexPath
}

cellForRow中设置单元格时,请将按钮的tag属性设置为单元格的indexPath.row。然后将方法签名更改为以下内容:

@IBAction func cellPlayButtonPressed(_ sender: UIButton) {
// sender.tag == indexPath.row
}

如果您的按钮不是UIButton的类,则可以将其替换为您的类。

当您在cellForRowAtIndexPath中时,您可以发送单元格的indexPath。然后你可以访问 indexPath。

func cellForRowAtIndex(_ tableView: UITableView, _ indexPath:IndexPath) -> UITableViewCell {
let UITableViewCell =  tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self), for: indexPath) as! UITableViewCell
cell.indexPath = indexPath
return cell

}

@IBAction func cellPlayButtonPressed(_ sender: UIButton) {
}

最新更新