简体   繁体   English

self.navigationController?来自UIAlertController的.popViewControllerAnimated

[英]self.navigationController?.popViewControllerAnimated from UIAlertController

I'm new to swift but I think I'm getting a hang of it. 我是新手,但我想我已经掌握了它。 This stumped my progress pretty hard though. 这让我的进步很难过。

What I want to do is to throw an error message to the user when we can't find relevant data to his query, and then proceed to take him back to the previous ViewController. 我想要做的是当我们无法找到他的查询的相关数据时向用户抛出错误消息,然后继续将他带回到之前的ViewController。

However, I'm having real trouble doing this. 但是,我在这方面遇到了麻烦。 On the line where I add the action I get the following error: 'UIViewController?' 在我添加操作的行上,我收到以下错误:'UIViewController?' is not a subtype of Void 不是Void的子类型

let alertController = UIAlertController(title: "Oops", message: "We couldn't find any data for this title, sorry!", preferredStyle: UIAlertControllerStyle.Alert)

alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
    self.navigationController?.popViewControllerAnimated(true)   
}))

How do I do this? 我该怎么做呢? Am I missing something obvious? 我错过了一些明显的东西吗 I tried messing around with the deprecated UIAlertView but became none the wiser. 我试着搞砸了被弃用的UIAlertView,但却没有变得更聪明。

Just add an explicit return statement in the closure body: 只需在闭包体中添加一个显式的return语句:

alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
    self.navigationController?.popViewControllerAnimated(true)
    return
}))

The reason why that happens is that a single statement closure is handled as the return value, so the compiler uses the return value of popViewControllerAnimated , which unsurprisingly is a UIViewController? 发生这种情况的原因是单个语句闭包被处理为返回值,因此编译器使用popViewControllerAnimated的返回值,这不足为奇是UIViewController? . The explicit return statement avoids that. 显式返回语句避免了这种情况。

This behavior is documented in Implicit Returns from Single-Expression Closures 单表达式闭包的隐式返回中记录了此行为

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM