通过操作表按钮传递值

时间:2016-10-20 12:14:34

标签: swift firebase swift3 nsindexpath

我使用按钮操作创建了ActionSheet。我有按钮打开操作表,ActionSheet按钮打开新的viewController。问题是打开操作表的按钮在tableview cell内,我不知道如何使用此按钮传递值。

概念应该是这样的,但是使用操作表按钮:

    actionSheet.addAction(UIAlertAction(title: "Edit it", style: UIAlertActionStyle.destructive, handler: { (ACTION :UIAlertAction!)in
            //here I want to pass value to next viewController and open that VC.
           //Valu should be something like postsArray[indexPath.row]
  }))

2 个答案:

答案 0 :(得分:1)

On button action you are showing the ActionSheet and you want that button's index on prepareforSegue method, so you need to store the IndexPath of tapped button on the action of button and then present the ActionSheet for that declare one instance of type IndexPath and use it inside your button action.

var selectedIndexPath = IndexPath()

@IBAction func buttonTapped(_ sender: UIButton) {
    let point = tableView.convert(CGPoint.zero, from: sender)
    if let indexPath = tableView.indexPathForRow(at: point) {
        self.selectedIndexPath = indexPath
        //Add code for presenting ActionSheet
    }
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "editPost" {
        let dest = segue.destination as! EditPostViewController
        dest.selectedPost = postsArray[self.selectedIndexPath.row]
    }
}

答案 1 :(得分:1)

尝试使用委托方法。

protocol ActionSheetDelegate{
   func transferSomeData(message : String)
  }

class customCell : UITableViewCell {

  var customCellDelegate : ActionSheetDelegate!

  ...
    actionSheet.addAction(UIAlertAction(title: "Edit it", style: UIAlertActionStyle.destructive, handler: { (ACTION :UIAlertAction!)in
        self.customCellDelegate.transferSomeData(message : "yourMessage")
     })
    )
  ...


}

在您当前的 tableViewController

class yourTableViewController : UITableViewController, UITableViewDelegate, UITableViewDataSource, ActionSheetDelegate {

 override func viewDidLoad(){


    }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

     let cell = customTableView.dequeueReusableCell(withIdentifier: "customCell") as! customTableViewCell 

     cell.customCellDelegate = self

     return cell 

   }

 func transferSomeData(message : String){

       print(message)
       // Segue to someViewController

     }
  }