按下按钮即可获取CollectionViewCell的IndexPath

我正在尝试获取单击按钮的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主题的帖子很多,但是没有一个能够解决我的问题。有人知道出了什么问题吗?

zys2229888 回答:按下按钮即可获取CollectionViewCell的IndexPath

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

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

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

cell.delegate = self
本文链接:https://www.f2er.com/3142192.html

大家都在问