将参数传递给Swift中的Action函数

时间:2017-02-07 20:47:54

标签: ios swift xcode uitableview

我使用动作创建了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。

3 个答案:

答案 0 :(得分:0)

您不必执行选择单元格的功能,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)")
}

答案 1 :(得分:0)

使用didSelectRowAt Indexpath方法。

对于自定义Tap使用以下步骤。

  1. 为您的单元格分配标记。

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

    cell.tag = indexPath.row  
    cell.addGestureRecognizer(tapGesture)
    
  2. 2.管理点击事件

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

    希望它有所帮助。 :)

答案 2 :(得分:0)

首先,删除点按手势。第二个实现didSelectRow的{​​{1}}代理,如下所示:

tableView

}

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