如何使用Swift在iOS中关闭视图控制器。

4

我有一个只包含ImageView的ViewController。我想在应用程序中出现加载时(例如从Web服务获取数据),将其呈现出来。因此,我在我的loaderViewController中创建了一个函数。

func showLoading(viewController:UIViewController) {
    viewController.presentViewController(LoadingViewController(), animated: false, completion: nil)
}

当我像下面这样在需要时调用此函数时,它按预期工作。
var loader = LoadingViewController()
loader.showLoading(self)

它展示了一个带有图片的视图控制器。

但是现在我想在需要时关闭这个视图控制器,但我无法做到,这是我迄今为止尝试过的,我在我的LoaderViewController中创建了另一个函数

func dismissLoader() {
    let load = LoadingViewController()
    load.dismissViewControllerAnimated(true) {
        print("Dismissing Loader view Controller")
    }
}

但是它没有起作用,视图控制器没有从屏幕上消失。
请指导我。

YASLoadingViewController和LoadingViewController是相同的吗? - Vishal Sonawane
6个回答

12

你不需要创建一个新的加载器实例并在其上调用dismissViewControllerAnimated(_:Bool)方法。

只需调用

self.dismissViewControllerAnimated(true)

在您的视图控制器上

因此,你的函数将是

func dismissLoader() {

    dismissViewControllerAnimated(true) {
        print("Dismissing Loader view Controller")
    }
}

你能帮我重写 dismissLoader 函数吗? - Byte

5
在Swift 3中,您可以执行以下操作。
self.dismiss(animated: true)

1
不要每次都创建 YASLoadingViewController(),这样会创建不同的控制器。 只需创建一次,然后使用 load 来解除或呈现。

这是一个答案吗? - Byte
1
你的答案通常是正确的,但如果你能提供更广泛的解释,它们将会非常有用。我认为提问者经常不够资格理解你的简短回答。 - Shadow Of

1
self.dismissViewControllerAnimated(false, completion: nil)

1
你的代码存在许多缺陷。你尝试实现这个功能的方式并不是一个好的做法。但是,如果你想快速修复问题,并且只想修改现有的方法,请按照以下步骤操作:
func dismissLoader() {
    self.dismissViewControllerAnimated(true) 
    print("Dismissing Loader view Controller")
}

当您展示一个新的LoadingViewController时,请保留对它的引用,以便您可以调用上面的方法。

无论如何,即使您没有保留引用,上面的代码也应该可以工作,因为如果在调用的ViewController上没有可用的已呈现ViewController,iOS将此方法委托回其父ViewController的层次结构。


1

您需要在父视图控制器中存储 LoadingViewController 的链接:

var loader: LoadingViewController?

func showLoadingIn(viewController: UIViewController) {
   loader = LoadingViewController() // create new instance before presentation
   viewController.presentViewController(loader!, animated: false, completion: nil)
}

func dismissLoader() {
    loader?.dismissViewControllerAnimated(true) {
        print("Dismissing Loader view Controller") 
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接