[iOS] How to show Actionsheet in iPad in swift
阿新 • • 發佈:2018-12-27
you should configure UIAlertController to be presented on a specific point on iPAD.
Example for navigation bar:
// 1
let optionMenu = UIAlertController(title: nil, message: "Choose an option", preferredStyle: .actionSheet)
// 2
let deleteAction = UIAlertAction(title: "Option 1", style : .default, handler: {
(alert: UIAlertAction!) -> Void in
print("option 1 pressed")
})
let saveAction = UIAlertAction(title: "Option 2", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("option 2 pressed")
})
// 3
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancelled")
})
// 4
optionMenu.addAction(deleteAction)
optionMenu.addAction(saveAction)
optionMenu.addAction(cancelAction)
// 5
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
optionMenu.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
optionMenu.popoverPresentationController?.permittedArrowDirections = .init(rawValue: 0)
optionMenu.popoverPresentationController?.sourceView = self.view
optionMenu.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
}
self.present(optionMenu, animated: true) {
print("option menu presented")
}
sample 2:
let alert = UIAlertController(title: "Alert Title", message: "Alert Message", style = .Alert)
for i in ["hearts", "spades", "diamonds", "hearts"] {
alert.addAction(UIAlertAction(title: i, style: .Default, handler: doSomething)
}
self.presentViewController(alert, animated: true, completion: nil)
And handle the action here:
func doSomething(action: UIAlertAction) {
//Use action.title
}
On an iPad, an action sheet is a popover. Therefore you must give its UIPopoverPresentationController a sourceView
and sourceRect
, or barButtonItem
, so that it has something to attach its arrow to.