在哪里可以找到关于 swift 警报(UIAlertController)的明确解释?

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

找不到对此的清晰且信息丰富的解释。

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

还可以,但对我来说不够清楚。

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

就是这样:

  1. UIAlertView 如指出的那样已弃用: UIAlertView in Swift
  2. UIAlertController应该用在iOS8+ 所以要首先创建一个我们需要实例化它, Constructor(init) 获取 3 个参数:

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

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

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

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

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

4.1 UIAlertController.addAction 创建按钮

4.2 UIAlertController.addTextField 创建文本字段

编辑注释: 下面的代码示例,更新为 swift 3 语法

示例 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);
}

示例 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);
}

示例 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);
 }

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

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.

不再授权

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.

行动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)
}

对于带文本字段的 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)
}

自最初的回复以来,一些语法发生了变化。下面是一些示例代码,可以在用户未登录 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")
        }
    }