ios 哪里可以找到关于 swift alert (UIAlertController) 的明确解释?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30276503/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 05:59:30  来源:igfitidea点击:

Where to find a clear explanation about swift alert (UIAlertController)?

iosswiftdialoguialertviewuialertcontroller

提问by Nikita Kurtin

Couldn't find a clear and informative explanation for this.

找不到对此的清晰而翔实的解释。

回答by Nikita Kurtin

After searching a while on a subject I didn't find a clear explanation , even in it's class reference UIAlertController Reference

在一个主题上搜索了一段时间后,我没有找到明确的解释,即使在它的类参考 UIAlertController 参考中

It is ok, but not clear enough for me.

没关系,但对我来说还不够清楚。

So after collecting some peaces I decided to make my own explanation (Hope it helps)

所以在收集了一些和平之后,我决定做出自己的解释(希望它有帮助)

So here it goes:

所以这里是这样的:

  1. UIAlertViewis deprecated as pointed out : UIAlertView in Swift
  2. UIAlertControllershould be used in iOS8+ so to create one first we need to instantiate it, the Constructor(init) gets 3 parameters:
  1. UIAlertView已被弃用: Swift 中的 UIAlertView
  2. UIAlertController应该在 iOS8+ 中使用,所以要先创建一个我们需要实例化它,Constructor(init) 获得 3 个参数:

2.1 title:String -> big-bold text to display on the top of alert's dialog box

2.1 title:String -> 显示在警报对话框顶部的大粗体文本

2.2 message:String -> smaller text (pretty much explains it's self)

2.2 message:String -> 较小的文本(几乎可以解释它的自我)

2.3 prefferedStyle:UIAlertControllerStyle-> define the dialog box style, in most cases: UIAlertControllerStyle.Alert

2.3 prefferedStyle:UIAlertControllerStyle-> 定义对话框样式,大多数情况下:UIAlertControllerStyle.Alert

  1. Now to actually show it to the user, we can use showViewControlleror presentViewControllerand pass our alert as parameter

  2. To add some interaction with a user we can use:

  1. 现在要实际向用户显示它,我们可以使用 showViewControlleror presentViewController并将我们的警报作为参数传递

  2. 要添加与用户的一些交互,我们可以使用:

4.1 UIAlertController.addActionto create buttons

4.1 UIAlertController.addAction创建按钮

4.2 UIAlertController.addTextFieldto create text fields

4.2 UIAlertController.addTextField创建文本字段

Edit note:code examples below, updated for swift 3 syntax

编辑说明:下面的代码示例,针对 swift 3 语法进行了更新

Example 1: Simple Dialog

示例 1:简单对话框

@IBAction func alert1(sender: UIButton) {
     //simple alert dialog
    let alert=UIAlertController(title: "Alert 1", message: "One has won", preferredStyle: UIAlertControllerStyle.alert);
    //show it
    show(alert, sender: self);
}

Example 2: Dialog with one input textField & two buttons

示例 2:具有一个输入文本字段和两个按钮的对话框

@IBAction func alert2(sender: UIButton) {
    //Dialog with one input textField & two buttons
    let alert=UIAlertController(title: "Alert 2", message: "Two will win too", preferredStyle: UIAlertControllerStyle.alert);
    //default input textField (no configuration...)
    alert.addTextField(configurationHandler: nil);
    //no event handler (just close dialog box)
    alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.cancel, handler: nil));
    //event handler with closure
    alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction) in
        let fields = alert.textFields!;
        print("Yes we can: "+fields[0].text!);
    }));
    present(alert, animated: true, completion: nil);
}

Example 3: One customized input textField & one button

示例 3:一个自定义输入文本字段和一个按钮

@IBAction func alert3(sender: UIButton) {
   // one input & one button
   let alert=UIAlertController(title: "Alert 3", message: "Three will set me free", preferredStyle: UIAlertControllerStyle.alert);

    //configured input textField
    var field:UITextField?;// operator ? because it's been initialized later
    alert.addTextField(configurationHandler:{(input:UITextField)in
        input.placeholder="I am displayed, when there is no value ;-)";
        input.clearButtonMode=UITextFieldViewMode.whileEditing;
        field=input;//assign to outside variable(for later reference)
    });
    //alert3 yesHandler -> defined in the same scope with alert, and passed as event handler later
    func yesHandler(actionTarget: UIAlertAction){
        print("YES -> !!");
        //print text from 'field' which refer to relevant input now
        print(field!.text!);//operator ! because it's Optional here
    }
    //event handler with predefined function
    alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: yesHandler));

    present(alert, animated: true, completion: nil);
 }

Hope It helps, and good luck ;-)

希望它有帮助,祝你好运;-)

回答by Omer Waqas Khan

An instance of the UIAlertController can be presented modally on screen just as any other UIViewController using the presentViewController:animated:completion: method. What makes the UIAlertController instance differentiate between working as an ActionSheet or as an AlertView is the style parameter you pass when creating it.

UIAlertController 的实例可以像任何其他 UIViewController 一样使用 presentViewController:animated:completion: 方法以模态方式呈现在屏幕上。使 UIAlertController 实例区分作为 ActionSheet 或作为 AlertView 的原因是您在创建它时传递的样式参数。

No more delegation

不再委托

If you have used a UIActionSheet or UIAlertView, you know that the way to get a callback from it is for a class (in most cases the ViewController) to implement the UIActionSheetDelegate or UIAlertViewDelegate protocol. There are some open source projects that replaced this delegation pattern with block based callbacks, but the official APIs were never updated. UIAlertController does not use delegation. Instead, it has a collection of UIAlertAction items, that use closures (or blocks if you are using Objective-C) to handle user input.

如果您使用过 UIActionSheet 或 UIAlertView,您就会知道从中获取回调的方法是让类(在大多数情况下是 ViewController)实现 UIActionSheetDelegate 或 UIAlertViewDelegate 协议。有一些开源项目用基于块的回调替换了这种委托模式,但官方 API 从未更新。UIAlertController 不使用委托。相反,它有一个 UIAlertAction 项的集合,这些项使用闭包(或块,如果您使用的是 Objective-C)来处理用户输入。

For Action Sheet

对于行动表

@IBAction func showActionSheet(sender: AnyObject) {
  //Create the AlertController
  let actionSheetController: UIAlertController = UIAlertController(title: "Action Sheet", message: "Swiftly Now! 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
  }
  actionSheetController.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
    }
  actionSheetController.addAction(takePictureAction)
  //Create and add a second option action
  let choosePictureAction: UIAlertAction = UIAlertAction(title: "Choose From Camera Roll", style: .Default) { action -> Void in
    //Code for picking from camera roll goes here
    }
  actionSheetController.addAction(choosePictureAction)

  //Present the AlertController
  self.presentViewController(actionSheetController, animated: true, completion: nil)
}

For AlertView with Text Field

对于带有文本字段的 AlertView

@IBAction func showAlert(sender: AnyObject) {
  //Create the AlertController
  let actionSheetController: UIAlertController = UIAlertController(title: "Alert", message: "Swiftly Now! Choose an option!", preferredStyle: .Alert)

  //Create and add the Cancel action
  let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
    //Do some stuff
    }
  actionSheetController.addAction(cancelAction)
    //Create and an option action
  let nextAction: UIAlertAction = UIAlertAction(title: "Next", style: .Default) { action -> Void in
    //Do some other stuff
    }
  actionSheetController.addAction(nextAction)
  //Add a text field
  actionSheetController.addTextFieldWithConfigurationHandler { textField -> Void in
       //TextField configuration
     textField.textColor = UIColor.blueColor()
   }

   //Present the AlertController
   self.presentViewController(actionSheetController, animated: true, completion: nil)
}

回答by CliffAnd

Some of the syntax has changed since the original responses. Here is some sample code that alerts the user if they are not signed in to iCloud.

自原始响应以来,某些语法已更改。下面是一些示例代码,如果用户没有登录 iCloud,它会提醒用户。

CKContainer.default().accountStatus { (accountStatus, error) in
        switch accountStatus {
        case .available:
            print("iCloud Available")
        case .noAccount:
            print("No iCloud account")
            //simple alert dialog
            let alert=UIAlertController(title: "Sign in to iCloud", message: "This application requires iClound. Sign in to your iCloud account to write records. On the Home screen, launch Settings, tap iCloud, and enter your Apple ID. Turn iCloud Drive on. If you don't have an iCloud account, tap Create a new Apple ID", preferredStyle: UIAlertControllerStyle.alert);
            //no event handler (just close dialog box)
            alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil));
            //show it
            self.present(alert, animated: true, completion: nil)
        case .restricted:
            print("iCloud restricted")
        case .couldNotDetermine:
            print("Unable to determine iCloud status")
        }
    }