从Cell单击button,获取UITableViewCell的indexPath

请看这个图像

我在UITableViewCell有一个button(红色十字),点击那个button,我想获得UITableViewCell indexPath

现在我将标签分配给每个button,像这样cell.closeButton.tag = indexPath.section和点击button我得到这样的indexPath.section值:

 @IBAction func closeImageButtonPressed(sender: AnyObject) { data.removeAtIndex(sender.tag) tableView.reloadData() } 

这是正确的执行方式还是有没有其他干净的方式来做到这一点?

使用代表:

MyCell.swift:

 import UIKit //1. delegate method protocol MyCellDelegate { func btnCloseTapped(cell: MyCell) } class MyCell: UICollectionViewCell { @IBOutlet var btnClose: UIButton! //2. create delegate variable var delegate: MyCellDelegate? override func awakeFromNib() { super.awakeFromNib() // Initialization code } //3. assign this action to close button @IBAction func btnCloseTapped(sender: AnyObject){ //4. call delegate method //check delegate is not nil if let _ = delegate { delegate?.btnCloseTapped(self) } } } 

MyViewContoller.swift:

 //5. Conform to delegate method class MyViewContoller: UIViewController,UITableViewDataSource,UITableViewDelegate,MyCellDelegate { //6. Implement Delegate Method func btnCloseTapped(cell: MyCell) { //Get the indexpath of cell where button was tapped let indexPath = self.collectionView.indexPathForCell(cell) print(indexPath!.row) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as! MyCell //7. assign cell delegate to view controller cell.delegate = self return cell } } 

您也可以通过CGPoint获取NSIndexPath

 @IBAction func closeImageButtonPressed(sender: AnyObject) { var buttonPosition = sender.convertPoint(CGPointZero, to: self.tableView) var indexPath = self.tableView.indexPathForRow(atPoint: buttonPosition)! } 

尝试这个:-

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = (tableView.dequeueReusableCell(withIdentifier: "MainViewCell", forIndexPath: indexPath) as! MainTableViewCell) cell.myButton().addTarget(self, action: Selector("myClickEvent:event:"), forControlEvents: .touchUpInside) return cell } 

这个函数得到行点击的位置

 @IBAction func myClickEvent(_ sender: Any, event: Any) { var touches = event.allTouches()! var touch = touches.first! var currentTouchPosition = touch.location(inView: feedsList) var indexPath = feedsList.indexPathForRow(atPoint: currentTouchPosition)! print("position:\(indexPath.row)") } 

创build一个自定义类的UIButton并声明这样的存储的属性,并使用它从callFroRowAtIndexPath检索分配的indexPath。

 class VUIButton: UIButton { var indexPath: NSIndexPath = NSIndexPath() } 

这是完全certificate的解决scheme,您的indexPath在任何情况下都不会出错。 尝试一次。

在你的cellForRow中:

#import <objc/runtime.h>

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { setAssociatedObject(object: YOURBUTTON, key: KEYSTRING, value: indexPath) }

@IBAction func closeImageButtonPressed(sender: AnyObject) { let val = getAssociatedObject(object: sender, key: KEYSTROKING) }

这里val是你的indexPath对象,你可以传递任何对象,就像你可以指定传递单元对象,并在button操作中获得它。

 // // ViewController.swift // Table // // Created by Ngugi Nduung'u on 24/08/2017. // Copyright © 2017 Ngugi Ndung'u. All rights reserved. // import UIKit class ViewController: UITableViewController{ let identifier = "cellId" var items = ["item1", "2", "3"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.title = "Table" tableView.register(MyClass.self, forCellReuseIdentifier: "cellId") } //Return number of cells you need override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! MyClass cell.controller = self cell.label.text = items[indexPath.row] return cell } // Delete a cell when delete button on cell is clicked func delete(cell: UITableViewCell){ print("delete") if let deletePath = tableView.indexPath(for: cell){ items.remove(at: deletePath.row) tableView.deleteRows(at: [deletePath], with: .automatic) } } } class MyClass : UITableViewCell{ var controller : ViewController? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setUpViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("init(coder:) has not been implemented") } let label : UILabel = { let label = UILabel() label.text = "My very first cell" label.translatesAutoresizingMaskIntoConstraints = false return label }() let btn : UIButton = { let bt = UIButton(type: .system) bt.translatesAutoresizingMaskIntoConstraints = false bt.setTitle("Delete", for: .normal) bt.setTitleColor(.red, for: .normal) return bt }() func handleDelete(){ controller?.delete(cell: self) } func setUpViews(){ addSubview(label) addSubview(btn) btn.addTarget(self, action: #selector(MyClass.handleDelete), for: .touchUpInside) btn.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true label.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 16).isActive = true label.widthAnchor.constraint(equalTo: self.widthAnchor , multiplier: 0.8).isActive = true label.rightAnchor.constraint(equalTo: btn.leftAnchor).isActive = true } } 

这是一个完整的例子,将回答你的问题。

如何通过buttonselect器在Swift 4中获取单元格的索引button

 @objc func buttonClicked(_sender:UIButton){ let buttonPosition = sender.convert(CGPoint.zero, to: self.tableView) let indexPath = self.tableView.indexPathForRow(at:buttonPosition) let cell = self.tableView.cellForRow(at: indexPath) as! UITableViewCell print(cell.itemLabel.text)//print or get item }