问题描述
我目前在其中一个应用中有以下代码行。这是一个简单的 UIAlertView
。但是,从iOS 8开始,现在已弃用:
I currently have the following line of code in one of my apps. It is a simple UIAlertView
. However, as of iOS 8, this is now deprecated:
let alertView = UIAlertView(title: "Oops!", message: "This feature isn't available right now", delegate: self, cancelButtonTitle: "OK")
如何更新此设置以使用iOS 8+?我相信我必须改变一些东西到 UIAlertCotroller
,虽然我不太清楚是什么。
How do I update this to work with iOS 8+? I believe I have to change something to UIAlertCotroller
, though I'm not too sure what.
推荐答案
您需要使用 UIAlertController
。 非常简单,甚至包含一个用法示例在清单1中的文档的开头(确定它在ObjC中,而不是在Swift中,但它非常相似)。
You need to use UIAlertController
instead. To class documentation is pretty straightforward, even containing an usage example in Listing 1 at the very beginning of the doc (sure it's in ObjC and not in Swift but it's quite similar).
所以对于你的用例,这是怎么回事转换为(添加注释):
So for your use case, here is how it translates to (with added comments):
let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { _ in
// Put here any code that you would like to execute when
// the user taps that OK button (may be empty in your case if that's just
// an informative alert)
}
alert.addAction(action)
self.presentViewController(alert, animated: true){}
因此紧凑的代码看起来喜欢:
So the compact code will look like:
let alert = UIAlertController(title: "Oops!", message:"This feature isn't available right now", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.present(alert, animated: true){}
其中 self
这里应该是你的 UIViewController
。
其他提示:如果你需要调用那个在 UIViewController
的上下文之外显示警报的代码,(其中 self
不是 UIViewController
)您可以随时使用应用的根VC:
Additional tip: if you need to call that code that displays the alert outside of the context of an UIViewController
, (where self
is not an UIViewController
) you can always use the root VC of your app:
let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController
rootVC?.presentViewController(alert, animated: true){}
(但一般情况下,最好使用已知的 UIViewController
当你有一个 - 并且你通常会提出来自UIViewControllers的警报 - 或尝试根据您的背景获得最合适的一个,而不是依赖于此提示)
(But in general it's preferable to use a known UIViewController
when you have one — and you generally present alerts from UIViewControllers anyway — or try to get the most suitable one depending on your context instead of relying on this tip)
这篇关于如何从UIAlertView迁移(在iOS8中弃用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!