ios - 如何从 UIAlertView 迁移(在 iOS8 中已弃用)

标签 ios xcode swift swift2 xcode7

我目前在我的一个应用程序中有以下代码行。这是一个简单的 UIAlertView。但是,从 iOS 8 开始,这已被弃用:

let alertView = UIAlertView(title: "Oops!", message: "This feature isn't available right now", delegate: self, cancelButtonTitle: "OK")

如何更新它以与 iOS 8+ 一起使用?我相信我必须对 UIAlertCotroller 进行一些更改,尽管我不太确定是什么。

最佳答案

您需要改用 UIAlertController。至class documentation非常简单,甚至在文档的开头包含 list 1 中的用法示例(确保它在 ObjC 中而不是在 Swift 中,但它非常相似)。

因此对于您的用例,以下是它如何转换为(添加评论):

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){}

所以紧凑的代码看起来像:

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:

let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController
rootVC?.presentViewController(alert, animated: true){}

(但通常情况下,最好使用已知的 UIViewController — 并且您通常会显示来自 UIViewController 的警报 — 或者尝试根据您的上下文获取最合适的而不是依赖这个技巧)

关于ios - 如何从 UIAlertView 迁移(在 iOS8 中已弃用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30933965/

相关文章:

xcode - 如何编辑默认的 Xcode 模板?

ios - flutter/iOS : Could not determine bundle id

swift - 编辑部分UITextview

ios - 具有Alamofire下载功能的JWT认证

jquery - Soundcloud iframe 在 iOS 下停止工作

ios - append 两个数组给出 [__NSCFArray insertObject :atIndex:]: mutating method sent to immutable object'

iOS:处理多维 Plist

c++ - 在 XCode 上使用 SDL 框架时遇到问题

ios - 多个持久存储

iphone - 我的 GKMatch 没有玩家...?