关于Swift中collectionView单元内的UIButton行为的问题

时间:2019-09-23 08:03:50

标签: ios swift uicollectionview uinavigationcontroller uibutton

我使collectionView单元格成为动态类型,并将诸如图像,标题,作者等信息放入其中。这些信息是关于这本书的,我们在单元格的底部创建了一个“查看”按钮。当我按单元格

if let navigationController = segue.destination as? UINavigationController,
                let index = collectionView.indexPathsForSelectedItems?.first,

                let readBookController = navigationController.viewControllers.first as? ReadBookViewController {

                readBookController.bookNo = self.booksCategory?.books[index.row].bookNo
                readBookController.bookTitle = self.booksCategory?.books[index.row].bookTitle
            }

此代码可以正常工作。

但是当我按下单元格内的按钮时,按下单元格时的行为(let index = collectionView.indexPathsForSelectedItems? .First) =>该代码不会运行,只会移动VC。

是否有一种方法可以在单元格被按下时以及在单元格中按下按钮时将相同的数据传递给VC?

代码:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        switch (segue.identifier!) {
        case "TappedCellSegue":
            if let navigationController = segue.destination as? UINavigationController,
                let index = collectionView.indexPathsForSelectedItems?.first,

                let readBookController = navigationController.viewControllers.first as? ReadBookViewController {

                readBookController.bookNo = self.booksCategory?.books[index.row].bookNo
                readBookController.bookTitle = self.booksCategory?.books[index.row].bookTitle
            }
        case "TappedBtnSegue":    // Not working
            let readVC = self.storyboard?.instantiateViewController(withIdentifier: "ReadBookViewController") as! ReadBookViewController

            if let navigationController = segue.destination as? UINavigationController,
                let index = collectionView.indexPathsForSelectedItems?.first,

                let readBookController = navigationController.viewControllers.first as? ReadBookViewController {
                readBookController.bookNo = self.booksCategory?.books[index.row].bookNo
                readBookController.bookTitle = self.booksCategory?.books[index.row].bookTitle
            }

            self.present(readVC, animated:true, completion: nil)
        default:
            break
        }
    }

1 个答案:

答案 0 :(得分:1)

在cellForItemAt中,您可以为按钮添加Target并提供indexPath.row:

cell.Button.tag = indexPath.row cell.Button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside)

在buttonAction功能中:

@objc func buttonAction(_ sender: UIButton) {
    let index = sender.tag

    if let readBookController = navigationController.viewControllers.first as? ReadBookViewController {
        readBookController.bookNo = self.booksCategory?.books[index].bookNo
        readBookController.bookTitle = self.booksCategory?.books[index].bookTitle

        self.present(readBookController, animated: true, completion: nil)
}