gpt4 book ai didi

swift - #selector 的局部函数

转载 作者:行者123 更新时间:2023-11-28 09:52:01 25 4
gpt4 key购买 nike

我正在构建这个应用程序来显示我家乡周围的餐馆,并为他们提供菜单、营业时间和地址。我这里有这个功能,可以在 Collection View 中显示有关餐厅的信息

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! RestaurantCollectionViewCell

cell.addressLabel.text = addressArray[indexPath.row]
cell.restaurantNameLabel.text = restaurantArray[indexPath.row]
cell.openingTimeLabel.text = openingTimeArray[indexPath.row]
cell.chosenRestaurantButton.addTarget(self, action: #selector(getProducts), for: .touchUpInside)

return cell
}

这是我在 Collection View 函数中传递给#selector 的函数。问题是我需要 getProducts 函数中的 Collection View 函数的索引路径。我无法嵌套函数,它会抛出有关局部函数的错误。有什么方法可以在 getProducts 函数中获取索引路径?

func getProducts() {
let viewController = storyboard?.instantiateViewController(withIdentifier: "productsCollectionView") as! ProductsViewController
viewController.restaurantChosen = restaurantArray[indexPathVariable.row]
self.present(viewController, animated: true, completion: nil)
}

最佳答案

您不能对可重用单元格中的按钮执行此类操作。为什么不在 RestaurantCollectionViewCell 子类中使用委托(delegate)?

protocol RestaurantCollectionViewCellDelegate: class
{
func getProducts(indexPath: IndexPath)
}

class RestaurantCollectionViewCell: UICollectionViewCell
{
var indexPath: IndexPath!
weak var delegate: RestaurantCollectionViewCellDelegate?

@IBAction func buttonPressed(_ sender: UIButton)
{
self.delegate?.getProducts(indexPath: self.indexPath)
}
}

在您的 CollectionView Controller 中,只需像这样分配委托(delegate):

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, RestaurantCollectionViewCellDelegate
{
func getProducts(indexPath: IndexPath)
{
let viewController = storyboard?.instantiateViewController(withIdentifier: "productsCollectionView") as! ProductsViewController
viewController.restaurantChosen = restaurantArray[indexPath.row]
self.present(viewController, animated: true, completion: nil)
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCustomCVCell", for: indexPath) as! RestaurantCollectionViewCell
cell.indexPath = indexPath
cell.delegate = self
return cell
}
}

关于swift - #selector 的局部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45133473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com