gpt4 book ai didi

ios - 在 Swift 中将参数传递给操作函数

转载 作者:行者123 更新时间:2023-11-30 12:42:13 25 4
gpt4 key购买 nike

我使用一个操作创建了 tableView 单元格,我需要该操作来了解所选单元格的索引路径。我不知道如何将 indexPath 作为参数传递给操作或找到任何其他方法。以下是 tableView cellForRowAt 的代码以及要执行的操作:

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell", for: indexPath) as! CustomCell
cell.foodName.text = self.menuItems[indexPath.row]
//adding gesture recognizer with action Tap to cell
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(Tap(gesture:index:IndexPath.row)))
cell.addGestureRecognizer(tapGesture)
return cell
}

func Tap(gesture: UIGestureRecognizer , index: Int){
print("Tap")
//necessary so that the page does not open twice
//adding the rating view
let ratingVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "rating") as! RatingView
ratingVC.foodName = selectedItem
self.addChildViewController(ratingVC)
ratingVC.view.frame = self.view.frame
self.view.addSubview(ratingVC.view)
ratingVC.didMove(toParentViewController: self)
}

我不知道如何将 IndexPath.row 作为参数传递给 Tap。

最佳答案

您不必执行选择单元格的功能,UITableViewDelegate已经有这种行为了。

遵守 UITableViewDelegate并实现tableView(_:didSelectRowAt:)方法,您将能够获取所选单元格的 indexPath.row:

Tells the delegate that the specified row is now selected

因此,在实现 tableView(_:didSelectRowAt:) 后,您应该摆脱 tapGesture 功能,它应该类似于:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell", for: indexPath) as! CustomCell
cell.foodName.text = self.menuItems[indexPath.row]

return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Selected row: \(indexPath.row)")
}

关于ios - 在 Swift 中将参数传递给操作函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42099696/

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