来自Cell的Button获取UITableViewCell的i

来自Cell的Button获取UITableViewCell的i

本文介绍了单击来自Cell的Button获取UITableViewCell的indexPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 UITableViewCell中有一个按钮(红色十字)并点击该按钮我想获得 UITableViewCell indexPath

I have a button (red color cross) in the UITableViewCell and on click of that button I want to get indexPath of the UITableViewCell.

现在我正在为每个按钮分配标签,如
cell.closeButton.tag = indexPath.section
和点击按钮我得到 indexPath.section 这样的值:

Right now I am assigning tag to each of the button like thiscell.closeButton.tag = indexPath.sectionand the on click of the button I get the indexPath.section value like this:

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

这是正确的实施方式还是有其他干净的方式来做到这一点?

Is this the right way of implementation or is there any other clean way to do this?

推荐答案

使用代表:

MyCell.swift:

import UIKit

//1. delegate method
protocol MyCellDelegate: AnyObject {
    func btnCloseTapped(cell: MyCell)
}

class MyCell: UICollectionViewCell {
    @IBOutlet var btnClose: UIButton!

    //2. create delegate variable
    weak var delegate: MyCellDelegate?

    //3. assign this action to close button
    @IBAction func btnCloseTapped(sender: AnyObject) {
        //4. call delegate method
        //check delegate is not nil with `?`
        delegate?.btnCloseTapped(cell: self)
    }
}

MyViewController.swift:

//5. Conform to delegate method
class MyViewController: 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
    }
}

这篇关于单击来自Cell的Button获取UITableViewCell的indexPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:27