按下按钮即可获取CollectionViewCell的IndexPath

时间:2019-11-07 19:09:36

标签: ios swift uicollectionview

我正在尝试获取单击按钮的indexPath.row来执行删除操作,并尝试对下一个控制器进行确认。

我有一个带有学生列表的collectionView,其中的单元格中有一个按钮,如果我单击该按钮,它应该对控制器执行搜索,以确认操作。现在的问题我似乎无法获取indexPath。我已经完成了一些研究和发现here的类似文章。当我尝试键入self.collectionView.indexPathForCell(cell)时,我设法完成了第6步。显示错误

  

对成员'collectionView(_:numberOfItemsInSection :)'的不明确引用

代理

protocol myCellDelegate: AnyObject {
    func deletePressed(cell: myCells)
}


class myCells : UICollectionViewCell{
    @IBOutlet weak var studentName: UILabel!
    @IBOutlet weak var deleteButton: UIButton!

    weak var delegate: myCellDelegate?


    @IBAction func deleteClicked(_ sender: Any) {
        delegate?.deletePressed(cell: self)
    }
}

ViewController

class RoomDetailViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource,myCellDelegate {


    func deletePressed(cell: myCells) {
        let indexPath = self.collectionView.indexPathForCell(cell)
    }



    var selectedCell = 0


    var students = ["Brandon","Brenda","Louise","Angela","Arthur"]

    override func viewDidLoad() {
        super.viewDidLoad()
        customBackButton()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.students.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! myCells

        cell.studentName.text = students[indexPath.item]
        selectedCell = indexPath.row

        return cell
    }

}

我知道关于这个indexPath主题的帖子很多,但是没有一个能够解决我的问题。有人知道出了什么问题吗?

1 个答案:

答案 0 :(得分:0)

这是一个集合视图,而不是表视图。使用indexPath(for:),而不是indexPathForCell

let indexPath = self.collectionView.indexPath(for: cell)

您还需要在cellForItemAt中设置单元格的委托:

cell.delegate = self