ios 如何从 UIAlertView 迁移(iOS8 中已弃用)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30933965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I migrate from UIAlertView (deprecated in iOS8)
提问by Dom Bryan
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:
我目前在我的一个应用程序中有以下代码行。这是一个简单的UIAlertView
. 但是,从 iOS 8 开始,这已被弃用:
let alertView = UIAlertView(title: "Oops!", message: "This feature isn't available right now", delegate: self, cancelButtonTitle: "OK")
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.
如何更新它以适用于 iOS 8+?我相信我必须将某些内容更改为UIAlertCotroller
,尽管我不太确定是什么。
回答by AliSoftware
You need to use UIAlertController
instead. To class documentationis 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).
你需要UIAlertController
改用。To class 文档非常简单,甚至在文档的开头包含清单 1 中的用法示例(当然它在 ObjC 中而不是在 Swift 中,但它非常相似)。
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){}
Where self
here is supposed to be your UIViewController
.
凡self
在这里应该是你的UIViewController
。
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:
附加提示:如果您需要调用在UIViewController
, (其中self
不是UIViewController
)的上下文之外显示警报的代码,您始终可以使用应用程序的根 VC:
let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController
rootVC?.presentViewController(alert, animated: true){}
(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)
(但一般来说,UIViewController
当你有一个时最好使用已知的——而且你通常会从 UIViewControllers 呈现警报——或者尝试根据你的上下文获得最合适的一个,而不是依赖这个技巧)
回答by RWIL
For those wondering on how to do this in Objective-C:
对于那些想知道如何在 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];
This will pop-up an alert that looks like this:
这将弹出一个警告,如下所示:
回答by Miknash
let alertView = UIAlertView(title: "Oops!", message: "This feature isn't available right now", delegate: self, cancelButtonTitle: "OK")
becomes
变成
let alertController = UIAlertController(title: "Oops!", message: "This feature isn't available right now", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in }
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) { }
回答by zveljkovic
I think this is the way to have backward compatibility for older iOS SDK and to use new API when using newer SDK. Also it is without warnings for deprecation in code using deprecated class.
我认为这是对较旧的 iOS SDK 向后兼容并在使用较新的 SDK 时使用新 API 的方法。此外,使用弃用类的代码中也没有弃用警告。
if ([UIAlertController class]) {
// Use new API to create alert controller, add action button and display it
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"CityBoard" message:error.errorDescription preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle: @"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
[alertController dismissViewControllerAnimated:YES completion:nil];
}];
[alertController addAction: ok];
[self presentViewController:alertController animated:YES completion:nil];
} else {
// We are running on old SDK as the new class is not available
// Hide the compiler errors about deprecation and use the class available on older SDK
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"CityBoard"
message:error.errorDescription
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
#pragma clang diagnostic pop
回答by A.G
Swift 2.0:
斯威夫特 2.0:
Use AlertController.
使用警报控制器。
Example for Action Sheet:
操作表示例:
let mediaActionSheet: UIAlertController = UIAlertController(title: "Media Action Sheet", message: "Choose an option!", preferredStyle: .ActionSheet)
//Create and add the Cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Just dismiss the action sheet
}
mediaActionSheet.addAction(cancelAction)
//Create and add first option action
let takePictureAction: UIAlertAction = UIAlertAction(title: "Take Picture", style: .Default) { action -> Void in
//Code for launching the camera goes here
}
mediaActionSheet.addAction(takePictureAction)
//Create and add a second option action
let choosePictureAction: UIAlertAction = UIAlertAction(title: "Choose From Gallery", style: .Default) { action -> Void in
//Code for picking from gallery goes here
}
mediaActionSheet.addAction(choosePictureAction)
//Present the AlertController
self.presentViewController(mediaActionSheet, animated: true, completion: nil)
Example for Alerts:
警报示例:
1)
1)
let simpleAlert = UIAlertController(title: "Simple Alert", message: "It is just awesome", preferredStyle: UIAlertControllerStyle.Alert);
//show it
showViewController(simpleAlert, sender: self);
2) Alert With TextField in it.
2) 带有 TextField 的警报。
let inputTextFieldAlert:UIAlertController = UIAlertController(title: " Input TextField Alert ", message: " Enter on the below TextField ", preferredStyle: UIAlertControllerStyle.Alert);
//default input textField (no configuration...)
inputTextFieldAlert.addTextFieldWithConfigurationHandler(nil);
//no event handler (just close dialog box)
inputTextFieldAlert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.Cancel, handler: nil));
//event handler with closure
inputTextFieldAlert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: {(action:UIAlertAction) in
let fields = inputTextFieldAlert.textFields!;
print("Output: "+fields[0].text!);
}));
presentViewController(inputTextFieldAlert, animated: true, completion: nil);
3)
3)
var alert = UIAlertController(title: "TextField Alert", message: "Enter on the below TextField", preferredStyle: UIAlertControllerStyle.Alert);
//configured input textField
var field:UITextField?;
alert.addTextFieldWithConfigurationHandler({(input:UITextField)in
input.placeholder="Empty Dtaa ;-)";
input.clearButtonMode=UITextFieldViewMode.WhileEditing;
field=input;
});
//YES Handler
func yesHandler(actionTarget: UIAlertAction){
print(field!.text!);
}
//event handler with predefined function
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default, handler: yesHandler));
presentViewController(alert, animated: true, completion: nil);
回答by Torongo
https://github.com/nagibazad/UIAlertControllerWrapper
https://github.com/nagibazad/UIAlertControllerWrapper
This wrapper provides a way of converting UIAlertView to UIAlertController easily. UIAlertView
is deprecated from iOS 9.0
. Convert your UIAlertView
of old projects to UIAlertController
keeping your delegate implementation remain same using this UIAlertControllerWrapper
and get rid of all the UIAlertView
related warnings
.
这个包装器提供了一种将 UIAlertView 轻松转换为 UIAlertController 的方法。UIAlertView
从iOS 9.0
. 使用此转换您UIAlertView
的旧项目以UIAlertController
保持您的委托实现保持不变UIAlertControllerWrapper
并摆脱所有UIAlertView
相关的warnings
.
回答by Nithinbemitk
You can use this code for Alert view :
您可以将此代码用于警报视图:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
For multiple buttons you can use :
对于多个按钮,您可以使用:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"Button 1" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self loadGooglrDrive];
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"Button 2" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self loadDropBox];
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
[self closeAlertview];
}]];
dispatch_async(dispatch_get_main_queue(), ^ {
[self presentViewController:alertController animated:YES completion:nil];
});
-(void)closeAlertview
{
[self dismissViewControllerAnimated:YES completion:nil];
}
回答by MB_iOSDeveloper
The examples above didn't help me much. My solution is for XCode 6.4., Swift 1.2 and you can copy and paste this code in a test project to get a feeling how it works :
上面的例子对我没有多大帮助。我的解决方案适用于 XCode 6.4.,Swift 1.2,您可以将此代码复制并粘贴到测试项目中,以了解其工作原理:
SOLUTION 1 - Swift 1.2 :
解决方案 1 - Swift 1.2:
import UIKit
let ALERT_TITLE = "Got you working, right?"
let ALERT_MESSAGE = "Well maybe..."
class ViewController: UIViewController
{
private var alert: UIAlertController!
private var presentAlertButton: UIButton!
override func viewDidAppear(animated: Bool)
{
/*
// QUICK TEST - 1
self.presentViewController(alert, animated: true, completion: nil)
*/
// QUCIK TEST - 2
/*
let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController
rootVC?.presentViewController(alert, animated: true, completion: nil)
*/
}
override func viewDidLoad()
{
super.viewDidLoad()
createAndAddAlertV()
createAndAddAlertButton()
}
private func createAndAddAlertV()
{
alert = UIAlertController(title:ALERT_TITLE, message:ALERT_MESSAGE, preferredStyle: .Alert)
let alertAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(alertAction)
}
private func createAndAddAlertButton()
{
presentAlertButton = UIButton(frame: CGRectMake(
view.frame.size.width / 2,
view.frame.size.height / 2,
200,
100))
presentAlertButton.layer.anchorPoint = CGPointMake(1.0, 1.0)
presentAlertButton.backgroundColor = UIColor.redColor()
presentAlertButton.setTitle("Click For Alert", forState: .Normal)
presentAlertButton.addTarget(self, action: "showAlertV", forControlEvents: .TouchUpInside)
self.view.addSubview(presentAlertButton)
}
@IBAction func showAlertV()
{
println(" Showing... ")
self.presentViewController(alert, animated: true, completion: nil)
}
}
I checked this solution in Xcode 7.0. It worked. Xcode made one change. I recompiled it in Xcode 6.4 again and it worked. The changes for Swift 2.0 should be minor if existent at all.
我在 Xcode 7.0 中检查了这个解决方案。有效。Xcode 进行了一项更改。我再次在 Xcode 6.4 中重新编译它并且它起作用了。如果存在的话,Swift 2.0 的变化应该很小。
Hope this helps ;)
希望这可以帮助 ;)