0

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

我有一个collectionView,其中包含学生列表,其中单元格中有一个按钮,如果我单击该按钮,它应该对控制器执行segue 以确认操作。现在的问题我似乎无法获得 indexPath。我已经完成了一些在这里找到的研究和类似的帖子。当我尝试输入self.collectionView.indexPathForCell(cell). 显示错误

对成员 '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)
    }
}

视图控制器

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主题的帖子,但没有一个能够解决我的问题。有谁知道出了什么问题?

4

1 回答 1

0

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

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

您还需要在以下位置设置单元格的委托cellForItemAt

cell.delegate = self
于 2019-11-07T19:14:17.620 回答