我試圖獲得與 Apple 在 iOS15 的日歷應用程式中所做的相同的行為(也可能在早期版本中),如果您嘗試關閉視圖,您將收到一個操作表,詢問您是否要放棄更改。
所以我想要的是能夠以某種方式捕捉到用戶嘗試向下拖動視圖并例如檢查的事件:
if hasChanges {
// Show Action sheet & stop view from disappearing
}
這不起作用,因為我不想在 viewWillDisappear 中作業,因為視圖在我開始展示操作表之前就消失了

uj5u.com熱心網友回復:
如 Apple檔案中所述,您可以實作UIAdaptivePresentationControllerDelegate并使用presentationControllerDidAttemptToDismiss(_ :)“攔截”下拉操作。
這是一個簡單的例子:
class ConfirmDismissViewController: UIViewController, UIAdaptivePresentationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemYellow
// add a dismiss button
let b = UIButton(type: .system)
b.setTitle("Dismiss", for: [])
b.addTarget(self, action: #selector(btnTapped(_:)), for: .touchUpInside)
b.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(b)
NSLayoutConstraint.activate([
b.centerXAnchor.constraint(equalTo: view.centerXAnchor),
b.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
// this will trigger a call to presentationControllerDidAttemptToDismiss() on drag-down
isModalInPresentation = true
presentationController?.delegate = self
}
func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// Only ask if the user wants to save if they attempt to pull to dismiss, not if they tap Cancel.
alert.addAction(UIAlertAction(title: "Discard Changes", style: .destructive) { _ in
self.dismiss(animated: true, completion: nil)
})
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
@objc func btnTapped(_ sender: Any?) -> Void {
// dismiss WITHOUT prompt
dismiss(animated: true, completion: nil)
}
}
當您呈現此視圖控制器時,用戶可以點擊“關閉”按鈕以明確關閉 VC,或者,如果用戶向下拖動,您將收到提示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/373454.html
