问题描述
在这种情况下,我使用 uialertcontroller 通知用户选择保存、放弃或取消更改。但是在消息出现之后和消失之前,执行之后的其他代码(makeNewDocument())。 我不确定是否有解决方案?
@objc func deletetoNew(_ notification: Notification) {
if AppDelegate.DocInEditing{
let dialogMessage = UIAlertController(title: "Save changes?",message: "This file belongs to \(UserManager.shared.firstname) \(UserManager.shared.lastname). Do you want to save changes?",preferredStyle: .alert)
let Yes = UIAlertAction(title: "Yes save",style: .default,handler: { (action) -> Void in
NotificationCenter.default.post(name: Notification.Name(rawValue: "saveChanges"),object: nil)
})
let No = UIAlertAction(title: "No discard changes",handler: { (action) -> Void in
})
let cancel = UIAlertAction(title: "Cancel",style: .cancel) { (action) -> Void in
return
}
dialogMessage.addAction(Yes)
dialogMessage.addAction(No)
dialogMessage.addAction(cancel)
present(dialogMessage,animated: true,completion: nil)
}
makeNewDocument()
}
解决方法
这是swift中的错误吗
没有
或者我的代码不正确(uialertcontroller)?
是的
警报控制器及其操作异步工作,要在完成时运行某些内容,需要使用 completion
参数。叫它
present(dialogMessage,animated: true,completion: makeNewDocument)
或者,如果您只想在其中一个操作中调用 makeNewDocument
,请将行移到操作正文中
let yes = UIAlertAction(title: "Yes save",style: .default,handler: { action in
NotificationCenter.default.post(name: Notification.Name(rawValue: "saveChanges"),object: nil)
self.makeNewDocument()
})
附注:
强烈建议仅在扩展中创建 Notification.Name
常量以利用这些常量的安全性
extension Notification.Name {
static let saveChanges = Notification.Name(rawValue: "saveChanges")
}
并使用它
let yes = UIAlertAction(title: "Yes save",handler: { action in
NotificationCenter.default.post(name: .saveChanges,object: nil)
self.makeNewDocument()
})