gpt4 book ai didi

PopUp 和 Dispatch 异步的快速计时

转载 作者:行者123 更新时间:2023-11-30 11:27:22 28 4
gpt4 key购买 nike

我是一名 swift 初学者,遇到了函数调用时间问题。我想要解释为什么会发生这种情况以及解决方法。问题出现在一个弹出窗口关闭时运行的代码段中,我想首先打开另一个弹出窗口,然后在新弹出窗口中按下按钮后,我希望程序在主视图 Controller 中另外执行一些操作。这是代码(有人建议使用 DispatchQue 但它似乎没有做任何事情):

@objc func onPopupClosed() {
print("first")

DispatchQueue.main.async {
if let vc = self.storyboard?.instantiateViewController (withIdentifier:
"P2CompetitionPopUpId") as? P2_Competition_Pop_Up
{
vc.modalPresentationStyle = .overCurrentContext
self.present(vc, animated: true, completion: nil)
} else {
print("error creating P2_Competion_Pop_Up")
}
}
print ("third")
}

P2_Competition_Pop_Up 如下所示:

class P2_Competition_Pop_Up: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

//print("Second")
}

@IBAction func Slot1(_ sender: Any) {

//some code

dismiss(animated: true, completion: nil)

}
}

我希望该程序输出“第一”“第二”“第三”(并且仅在弹出窗口中按下按钮后才打印“第三”。)。相反,它给了我“第一”“第三”“第二”。为什么?我该如何解决它?使用 DispatchQue 是正确的方法还是还有其他方法?

ps。 “print(“third”)”语句实际上是对主视图外观的修改。我只是用这个语句来突出顺序难度并简化说明。

最佳答案

无法保证您的代码中“Second”或“Third”将首先打印。但是,如果您希望在呈现 UIViewController 后完成某些操作,则应该在 present 完成 block 中完成。

    if let vc = self.storyboard?.instantiateViewController (withIdentifier: "P2CompetitionPopUpId") as? P2_Competition_Pop_Up {
vc.modalPresentationStyle = .overCurrentContext
self.present(vc, animated: true, completion: {
// do it here
print ("third")
})
} else {
print("error creating P2_Competion_Pop_Up")
}

你也可以用糖语法编写

      self.present(vc, animated: true) {
print ("third")
}

关于PopUp 和 Dispatch 异步的快速计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50592228/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com