Dom*_*yan 30 xcode ios swift xcode7 swift2
我目前在我的一个应用程序中有以下代码行.这很简单UIAlertView.但是,从iOS 8开始,现在不推荐使用它:
let alertView = UIAlertView(title: "Oops!", message: "This feature isn't available right now", delegate: self, cancelButtonTitle: "OK")
Run Code Online (Sandbox Code Playgroud)
如何更新此功能以使用iOS 8+?我相信我必须改变一些东西UIAlertCotroller,虽然我不太清楚是什么.
Ali*_*are 64
你需要UIAlertController改用.为了类文档是非常简单的,甚至包含在文档的开始清单1中的使用实例(确保它在ObjC而不是斯威夫特但它是非常相似).
因此,对于您的用例,以下是它的转换方式(添加了注释):
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){}
Run Code Online (Sandbox Code Playgroud)
所以紧凑的代码看起来像:
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){}
Run Code Online (Sandbox Code Playgroud)
凡self在这里应该是你的UIViewController.
附加提示:如果您需要调用UIViewController在self(不在其中UIViewController)的上下文之外显示警报的代码,您可以随时使用应用的根VC:
let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController
rootVC?.presentViewController(alert, animated: true){}
Run Code Online (Sandbox Code Playgroud)
(但总的来说,UIViewController当你有一个已知的时候最好使用已知的- 并且你通常会提出来自UIViewControllers的警报 - 或者根据你的上下文尝试获得最合适的警报,而不是依赖于这个提示)
RWI*_*WIL 33
对于那些想知道如何在Objective-C中执行此操作的人:
//Step 1: Create a UIAlertController
UIAlertController *myAlertController = [UIAlertController alertControllerWithTitle:@"MyTitle"
message: @"MyMessage"
preferredStyle:UIAlertControllerStyleAlert ];
//Step 2: Create a UIAlertAction that can be added to the alert
UIAlertAction* ok = [UIAlertAction
actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
//Do some thing here, eg dismiss the alertwindow
[myAlertController dismissViewControllerAnimated:YES completion:nil];
}];
//Step 3: Add the UIAlertAction ok that we just created to our AlertController
[myAlertController addAction: ok];
//Step 4: Present the alert to the user
[self presentViewController:myAlertController animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)
这将弹出一个如下所示的警报:
| 归档时间: |
|
| 查看次数: |
35880 次 |
| 最近记录: |