簡體   English   中英

如何從UIAlertView遷移(在iOS8中已棄用)

[英]How do I migrate from UIAlertView (deprecated in iOS8)

我目前在我的一個應用程序中有以下代碼行。 這是一個簡單的UIAlertView 但是,從iOS 8開始,現在不推薦使用它:

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

如何更新此功能以使用iOS 8+? 我相信我必須改變一些東西給UIAlertCotroller ,雖然我不太清楚是什么。

您需要使用UIAlertController 類文檔非常簡單,甚至在文檔的開頭包含清單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 - 你通常會從UIViewControllers提出警告 - 或者根據你的上下文嘗試獲得最合適的一個,而不是依賴於這個提示)

對於那些想知道如何在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];

這將彈出一個如下所示的警報:

警報示例

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

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

我認為這是為舊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

Swift 2.0:

使用AlertController。

操作表示例:

  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)

警報示例:

1)

let simpleAlert = UIAlertController(title: "Simple Alert", message: "It is just awesome", preferredStyle: UIAlertControllerStyle.Alert);

  //show it
  showViewController(simpleAlert, sender: self);

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)

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);

上面的例子對我沒什么幫助。 我的解決方案適用於XCode 6.4。,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)
    }

}

我在Xcode 7.0中檢查了這個解決方案。 有效。 Xcode做了一個改變。 我再次在Xcode 6.4中重新編譯它,它工作。 如果存在的話,Swift 2.0的更改應該是次要的。

希望這可以幫助 ;)

您可以將此代碼用於警報視圖:

 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];

對於多個按鈕,您可以使用:

 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];
}

https://github.com/nagibazad/UIAlertControllerWrapper

這個包裝器提供了一種將UIAlertView輕松轉換為UIAlertController的方法。 UIAlertView已從iOS 9.0棄用。 將您的UIAlertView的老項目,以UIAlertController保持你的委托執行使用此保持相同UIAlertControllerWrapper ,擺脫所有的UIAlertView的相關warnings

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM