3

I want to display an ActionSheet on both, iPhone and iPad devices. While my code works properly on iPhone's, it doesn't on iPad's. The reason for this is that I need to specify a location where to display the popover. As a result, I tried to used the code proposed in this answer. The problem that I currently have is, that I do not know how to pass the argument sender to the method.

For example, I have a UITableViewRowAction which when clicked should display the ActionSheet:

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {

        let rowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Action", handler:{action, indexpath in
            print("Action for element #\(indexPath.row).");
            self.displayActionSheet()
        });

        return [rowAction];
    }

Which argument is sender in my case? I am not able to pass rowAction to displayActionSheet(), because the variable is used within its own initial value. I also tried to pass self.displayDeleteLicencePlateActionSheet(self.items[indexPath.row]), but same result – I always end up in the else clause of the guard expression:

guard let button = sender as? UIView else {
            print("sender empty")
            return
}

I want to display also an ActionSheet when clicking on an UIBarButtonItem:

let myButton = UIBarButtonItem(title: "FooBar", style: .Plain, target: self, action: #selector(SecondViewController.displaySecondActionSheet(_:)))

But same result. How can this be done?

Community
  • 1
  • 1
John Doe
  • 277
  • 3
  • 14

1 Answers1

0

Please refer following code to fix your issue.

TARGET_OBJECT will be your sender where from you want to show an alert.

func showAlert() {
    let alert = UIAlertController(title: "Title", message: "Message text", preferredStyle: .alert)

    let actionOK = UIAlertAction(title: "OK", style: .default) { (alertAction) in
    }
    alert.addAction(actionOK)

    if let popoverController = alert.popoverPresentationController {
        popoverController.sourceView = self.TARGET_OBJECT // TARGET_OBJECT will be your sender to show an alert from.
        popoverController.sourceRect = CGRect(x: self.TARGET_OBJECT.frame.size.width/2, y: self.TARGET_OBJECT.frame.size.height/2, width: 0, height: 0)
    }

    UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
}

Please check attached image it will appear as you want.

enter image description here

Ayaz Rafai
  • 279
  • 2
  • 10