这是swift中的错误还是我的代码不正确uialertcontroller?

问题描述

在这种情况下,我使用 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()                        
          })

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...