【问题标题】:How to dismiss modal ViewController from UIAlertcontroller如何从 UIAlertcontroller 关闭模态 ViewController
【发布时间】:2023-03-07 22:22:01
【问题描述】:

我展示了一个模态viewcontroller,用户可以在该模态上决定编辑或删除显示的汽车。

如果用户想删除这辆车,我会提出一个带有警报样式的UIAlertController,询问他是否真的想删除这辆车。一切正常。但是在用户选择“Yes”之后,我仍然在modal viewcontroller

删除后如何关闭模态视图?

我尝试了以下代码

self.parentViewController?.dismissViewControllerAnimated(true, completion: nil)

self.navigationController?.popViewControllerAnimated(true)

在 ok Action 结束时,但两者都没有为我工作。 :(

【问题讨论】:

  • 如何调用dismissviewcontroller视图? (父视图或导航)分享一些屏幕截图或代码。
  • nishith Singh 的解决方案有效吗?
  • 不,它没有用

标签: ios swift uiviewcontroller modalviewcontroller uialertcontroller


【解决方案1】:

没有理由把代码写在

dispatch_async(dispatch_get_main_queue(), {    //write your code here

 })

以上代码用于在主线程中工作。但是在这里你已经在主线程上。

这里的问题是你在打电话

self.parentViewController?.dismissViewControllerAnimated(true, completion: nil)

直接写就行了

self.dismissViewControllerAnimated(true, completion: nil)

因为您在self 控制器上显示AlertController,所以唯一可以忽略它的是self

【讨论】:

  • 请查看以下链接,这可能是您正在寻找的原因:stackoverflow.com/questions/37488918/…
  • 好的 dispatch_get_main_queue() 总是可以正常工作的。但是我们应该只在我们的线程在后台并且我们想在主线程上更改 UI 时使用,在你的链接中,他做了一个很长的操作,而且总是在后台线程中完成,而不是让 UI 改变他做到了在 dispatch_get_main_queue() 中。我们应该小心使用这个主线程块,因为主线程中的长进程可能会阻塞 UI 并挂起您的设备。
  • 您知道 Fox 为确定按钮操作实施了哪些代码或处理。正如他已经提到的那样 self.dismissViewControllerAnimated(true, completion: nil) 对他不起作用,所以在确定按钮操作中,他有可能必须有一些在后台执行的代码,这就是为什么我建议他使用dispatch_get_main_queue()。我不明白您为什么对自己的想法如此刻板,以至于您不想了解给定解决方案起作用的可能原因。如果您不喜欢该解决方案,请自行解决。
  • 他从未说过/提到他尝试过 self.dismissViewControllerAnimated(true, completion: nil) :) ,如果他尝试过,那么他甚至可能不会遇到这个问题。
【解决方案2】:

把你的代码放在里面

 dispatch_async(dispatch_get_main_queue(), {    //write your code here

 })

像这样:

func showDeleteWarningAndDeleteEntity() {

    dispatch_async(dispatch_get_main_queue(), {  

         let deleteController = UIAlertController(title: "Delete car", message: "Are you sure?", preferredStyle: .Alert)
    let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) {
        (action) in
    }
    let okACtion = UIAlertAction(title: "Yes", style: .Destructive) {
        (action) in
        //some network stuff happens here...

        self.dismissViewControllerAnimated(true, completion: nil)
    }
    deleteController.addAction(okACtion)
    deleteController.addAction(cancelAction)
    self.presentViewController(deleteController, animated: true, completion: nil)
     })

}

希望这对你有用

【讨论】:

  • 在主线程上调度与为什么这对你有用无关。我认为你打电话给self.dismissViewControllerAnimated() 是真正解决问题的原因。
  • 是的@Mike,你是对的。主线程不是这里的解决方案。这应该是他驳回它的方式。
猜你喜欢
  • 1970-01-01
  • 2019-12-15
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
相关资源
最近更新 更多