I am using Xcode 6 to develop an iOS Application.
When I used UIAlertController
, it can be worked well on iPhone 6 simulator, but crashes on iPad simula
If you don't need presenting the alert as popover, you can simply use UIAlertController.Style.alert
as preferred style, when initializing AlertViewController
.
let shareMenu = UIAlertController(title: nil, message: "Share using", preferredStyle: .alert)
for iOS 13
used it.
if #available(iOS 13.0, *) {
if let popoverPresentationController = actionSheet.popoverPresentationController {
popoverPresentationController.sourceView = self.view
popoverPresentationController.sourceRect = sender.frame
}
self.present(actionSheet, animated: true, completion: nil)
} else {
actionSheet.popoverPresentationController?.sourceView = self.view
actionSheet.popoverPresentationController?.sourceRect = sender.frame
actionSheet.show()
}
try this code:
shareMenu.popoverPresentationController.sourceView = self.view
shareMenu.popoverPresentationController.sourceRect = CGRectMake(self.view.bounds.size.width / 2.0, self.view.bounds.size.height / 2.0, 1.0, 1.0)
self.presentViewController(shareMenu, animated: true, completion: nil)
Swift 4
popoverPresentationController.permittedArrowDirections = .init(rawValue: 0)
popoverPresentationController.sourceView = self.view
popoverPresentationController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
I use this handy extension to create action sheets that never crash
extension UIAlertController {
class func actionSheetWith(title: String?, message: String?, sourceView: UIView?, sourceFrame: CGRect?) -> UIAlertController {
let actionController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
if actionController.responds(to: #selector(getter: popoverPresentationController)) {
actionController.popoverPresentationController?.sourceView = sourceView ?? StoryboardHelper.tabBarControllerTopController()?.view
actionController.popoverPresentationController?.sourceRect = sourceFrame ?? CGRect(x: 0, y: 0, width: 0, height: 0)
}
return actionController
}
}
Swift 3
shareMenu.popoverPresentationController?.sourceView = self.view
shareMenu.popoverPresentationController?.sourceRect =
CGRect(x: view.bounds.size.width,
y: view.bounds.size.height-80,
width: 1.0, height: 1.0)
source rect is the point from were you want to show popover view.