class ViewController: UIViewController {
@IBAction func clicked(_ sender: Any) {
let vc = UIHostingController(rootView: AlertView(cancel: {
//
self.dismiss(animated: true)
}, done: { text in
if text.isEmpty {
return
}
self.dismiss(animated: true)
}))
vc.modalPresentationStyle = .popover
vc.preferredContentSize = CGSize(width: 200, height: 200)
let popoverVC = vc.popoverPresentationController
popoverVC?.permittedArrowDirections = []
popoverVC?.sourceView = view
popoverVC?.sourceRect = view.bounds
popoverVC?.delegate = self
popoverVC?.popoverLayoutMargins = .zero
popoverVC?.backgroundColor = .blue
present(vc, animated: true)
}
}
记得实现下面这个方法
extension ViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
}
extension UIView {
func showViewWithSpringAnimation(_ view: UIView, completion: (() -> Void)? = nil) {
view.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
view.center = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
// Animate the popover view into the screen
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: .curveEaseInOut, animations: {
view.transform = CGAffineTransform.identity
}) { completed in
if completed {
completion?()
}
}
}
func dismissWithAnimation(_ completion: (() -> Void)? = nil) {
UIView.animate(withDuration: 0.3) {
self.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
} completion: { completed in
if completed {
self.removeFromSuperview()
completion?()
}
}
}
}
@IBAction func clicked(_ sender: Any) {
let popoverView = UIView(frame: self.view.bounds)
popoverView.backgroundColor = UIColor.black.withAlphaComponent(0.2)
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
containerView.layer.cornerRadius = 10
containerView.backgroundColor = .red
popoverView.addSubview(containerView)
containerView.center = popoverView.center
popoverView.addGestureRecognizer(UITapGestureRecognizer(action: { _ in
popoverView.dismissWithAnimation()
}))
self.view.addSubview(popoverView)
self.view.showViewWithSpringAnimation(popoverView)
http://iphonedevwiki.net/index.php/UIAlertController
vc.preferredContentSize = CGSize(width: 270, height: 300)
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
alert.setValue(vc, forKeyPath: "contentViewController")
present(alert, animated: true)