问题
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