Pass value with action sheet button

こ雲淡風輕ζ 提交于 2019-12-25 07:54:17

问题


I created an ActionSheet with action of button. I have button that opens the action sheet and the ActionSheet button opens new viewController. The problem is that the button which opens the action sheet is inside tableview cell and I do not know how to pass value with this button.

The concept should be something like this but with the action sheet button:

    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]
  }))

回答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]
    }
}



回答2:


Try using delegate method.

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")
     })
    )
  ...


}

In your current 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

     }
  }


来源:https://stackoverflow.com/questions/40154153/pass-value-with-action-sheet-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!