在 Swift 中将参数传递给动作函数



我创建了一个带有动作的tableView单元格,我需要该动作来知道所选单元格的indexPath。我不知道如何将 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

告知代理指定的行现在已选中

因此,在实现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)")
}

使用 didSelectRowAt Indexpath 方法。

对于自定义点击,请使用以下步骤。

  1. 将标签分配给单元格。

    let tapGesture

    = UITapGestureRecognizer(target: self, action: #selector(self.tapBlurButton(_:

    (((
    cell.tag = indexPath.row  
    cell.addGestureRecognizer(tapGesture)
    

2.管理点击事件

func tapBlurButton(_ sender: UITapGestureRecognizer) {
   //Get indexpath.row value or Indexpath Value
print(sender.view.tag)
}

希望对您有所帮助。 :)

首先,删除点击手势。第二次实现tableViewdidSelectRow委托,如下所示:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//add your rating view code here
let ratingVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "rating") as! RatingView
ratingVC.foodName = self.menuItems[indexPath.row] //get the selected item
self.addChildViewController(ratingVC)
ratingVC.view.frame = self.view.frame
self.view.addSubview(ratingVC.view)
ratingVC.didMove(toParentViewController: self)

}

当然,您需要添加检查和防护以确保捕获任何错误。

最新更新