iOS警报– UIAlertController

时间:2020-02-23 14:45:53  来源:igfitidea点击:

在本教程中,我们将讨论UIAlertController类以及如何在我们的iOS应用程序中创建不同类型的警报。

iOS警报– UIAlertController

UIAlertController用于配置警报和操作表以及可供选择的各种操作。

在另一个教程中,我们已经有ActionSheets。
其中我们将重点介绍UIAlertController的警报样式。

除了动作,我们还可以添加图像徽标。
我们也可以在"警报"中设置文本字段输入,我们将很快看到。

UIAlertController通常用于要求用户打开一种类型的应用程序。
示例:呼叫/消息。
相机/画廊。

在不同的地图应用中选择。

默认警报

可以通过以下方式在Swift中创建基本的UIAlertController Alert对话框。

let alertController = UIAlertController(title: "theitroad.local", message: "Default Alert Dialog", preferredStyle: .alert)
      
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
      
self.present(alertController, animated: true, completion: nil)

传递标题,消息和首选样式。
UIAlertController中的每个Button都是一个UIAlertAction。

UIAlertAction按钮具有三种样式:默认,破坏性,取消。
破坏性风格为红色。

动作按钮

每个UIALertAction都有一个处理程序参数,我们其中添加要执行的动作的逻辑。

let alertController = UIAlertController(title: "theitroad", message: "Alert With Actions", preferredStyle: .alert)
      
      let action1 = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction) in
          print("You've pressed OK")
          alertController.dismiss(animated: true, completion: nil)
      }
      
      let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) in
          print("You've pressed Cancel")
      }
      
      let action3 = UIAlertAction(title: "Delete", style: .destructive) { (action:UIAlertAction) in
          print("You've pressed the destructive")
      }
      
      alertController.addAction(action1)
      alertController.addAction(action2)
      alertController.addAction(action3)
      self.present(alertController, animated: true, completion: nil)

在上面的代码中,我们在Swift闭包中添加了log语句。
您也可以在此处传递自己的自定义函数。

UIAlertController带调用,消息,打开地图

在以下代码中,我们的每个操作按钮都将用于呼叫,消息传递以及从"警报"对话框中打开第三方应用程序。

let application:UIApplication = UIApplication.shared
      
              let alert = UIAlertController(title: "Your Title", message: "Select one of the apps", preferredStyle: .alert)
      
      
              let callAction = UIAlertAction(title: "Call", style: .default, handler: { (action) in
                  let phoneNumber: String = "tel:/1234567890"
                  application.open(URL(string: phoneNumber)!, options: [:], completionHandler: nil)
              })
      
              let messageAction = UIAlertAction(title: "Message", style: .default, handler: { (action) in
                  application.open(URL(string: "sms:123456")!, options: [:], completionHandler: nil)
              })
      
              let mapsAction = UIAlertAction(title: "Apple Maps", style: .destructive, handler: { (action) in
                  
                  let targetURL = URL(string: "https://maps.apple.com/?q=cupertino")!
                  application.open(targetURL, options: [:], completionHandler: nil)
                  
              })
              alert.addAction(callAction)
              alert.addAction(messageAction)
              alert.addAction(mapsAction)
              
              self.present(alert, animated: true, completion: nil)

传递电话号码的网址架构为:" tel:/(phone_number_pass_here)"要打开第三方应用程序(例如Apple Maps),我们需要使用其预定义的自定义架构。

要打开Google Maps Application,我们首先需要检查该应用程序是否已安装:

if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!))
      {
          UIApplication.shared.openURL(URL(string:
              "comgooglemaps://?saddr=&daddr=\(Float(latitude!)),\(Float(longitude!))&directionsmode=driving")! as URL)
      } else
      {
          NSLog("Can't use com.google.maps://");
      }

添加图像徽标并启动URL

我们可以在每个操作按钮上添加图像徽标。

另外,我们可以设置一个动作,以在iOS设备的默认网络浏览器中启动URL。

let alertController = UIAlertController(title: "theitroad.local", message: "Alert Dialog with Image", preferredStyle: .alert)
      
      
      let imageAction = UIAlertAction(title: "Website", style: .default, handler: {
          (action) in
          UIApplication.shared.open(URL(string: "https://www.theitroad.local")!, options: [:], completionHandler: nil)
      })
      imageAction.setValue(UIImage(named: "logo")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), forKey: "image")
      
      let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
      okAction.setValue(UIColor.brown, forKey: "titleTextColor")
      
      alertController.addAction(imageAction)
      alertController.addAction(okAction)
      
      self.present(alertController, animated: true, completion: nil)

对于每个操作,我们可以设置在XCode项目的Assets文件夹中定义的图像文件名。

要为每个操作按钮设置相同的颜色,请执行以下操作:

alertController.view.tintColor = UIColor.orange

添加一个TextField

let alert = UIAlertController(title: "Login", message: "Please enter the details below", preferredStyle: .alert)
      
      alert.addTextField{ textField -> Void in
          textField.placeholder = "Username"
          textField.textColor = UIColor.blue
      }
      
      alert.addTextField{ textField -> Void in
          textField.placeholder = "Password"
          textField.textColor = UIColor.black
          textField.isSecureTextEntry = true
      }
      
      let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
      
      alert.addAction(cancelAction)
      
      self.present(alert, animated: true, completion: nil)

在addTextField函数内部,我们可以配置TextField。
所有的TextField将垂直堆叠。

让我们将所有这些合并到我们的XCode iOS应用程序中。

主机板

我们已经将每个Button连接到ViewController.swift,并为每个Button创建了IBAction函数。

在Assets文件夹中导入一个png图像文件。
确保密钥名称与您在下面的ViewController.swift中设置的密钥名称相同:

import UIKit

class ViewController: UIViewController {

  @IBAction func showAlert(_ sender: Any) {
      
      let alertController = UIAlertController(title: "theitroad.local", message: "Default Alert Dialog", preferredStyle: .alert)
      
      let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
      alertController.addAction(defaultAction)
      
      self.present(alertController, animated: true, completion: nil)
  }
  
  @IBAction func showAlertWithActions(_ sender: Any) {
      
      let alertController = UIAlertController(title: "theitroad", message: "Alert With Actions", preferredStyle: .alert)
      
      let action1 = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction) in
          print("You've pressed OK")
          alertController.dismiss(animated: true, completion: nil)
      }
      
      let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) in
          print("You've pressed Cancel")
      }
      
      let action3 = UIAlertAction(title: "Delete", style: .destructive) { (action:UIAlertAction) in
          print("You've pressed the destructive")
      }
      
      alertController.addAction(action1)
      alertController.addAction(action2)
      alertController.addAction(action3)
      self.present(alertController, animated: true, completion: nil)
  }
  
  @IBAction func showAlertWithTextField(_ sender: Any) {
      
      let alert = UIAlertController(title: "Login", message: "Please enter the details below", preferredStyle: .alert)
      
      alert.addTextField{ textField -> Void in
          //TextField configuration
          textField.placeholder = "Username"
          textField.textColor = UIColor.blue
      }
      
      alert.addTextField{ textField -> Void in
          //TextField configuration
          textField.placeholder = "Password"
          textField.textColor = UIColor.black
          textField.isSecureTextEntry = true
      }
      
      let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
      
      alert.addAction(cancelAction)
      
      self.present(alert, animated: true, completion: nil)
  }
  
  @IBAction func showAlertWithCallMapsMessage(_ sender: Any) {
      
      
              let application:UIApplication = UIApplication.shared
      
              let alert = UIAlertController(title: "Your Title", message: "Select one of the apps", preferredStyle: .alert)
      
      
              let callAction = UIAlertAction(title: "Call", style: .default, handler: { (action) in
                  let phoneNumber: String = "tel:/1234567890"
                  application.open(URL(string: phoneNumber)!, options: [:], completionHandler: nil)
              })
      
              let messageAction = UIAlertAction(title: "Message", style: .default, handler: { (action) in
                  application.open(URL(string: "sms:123456")!, options: [:], completionHandler: nil)
              })
      
      
      
              let mapsAction = UIAlertAction(title: "Apple Maps", style: .destructive, handler: { (action) in
                  
                  let targetURL = URL(string: "https://maps.apple.com/?q=cupertino")!
                  application.open(targetURL, options: [:], completionHandler: nil)
                  
              })
              alert.addAction(callAction)
              alert.addAction(messageAction)
              alert.addAction(mapsAction)
              
              self.present(alert, animated: true, completion: nil)
  }
  
  @IBAction func showAlertWithImageLogo(_ sender: Any) {
      
      let alertController = UIAlertController(title: "theitroad.local", message: "Alert Dialog with Image", preferredStyle: .alert)
      
      //alertController.view.tintColor = UIColor.orange
      
      let imageAction = UIAlertAction(title: "Website", style: .default, handler: {
          (action) in
          UIApplication.shared.open(URL(string: "https://www.theitroad.local")!, options: [:], completionHandler: nil)
      })
      imageAction.setValue(UIImage(named: "logo")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal), forKey: "image")
      
      let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
      okAction.setValue(UIColor.brown, forKey: "titleTextColor")
      
      alertController.addAction(imageAction)
      alertController.addAction(okAction)
      
      self.present(alertController, animated: true, completion: nil)
  }
  
  override func viewDidLoad() {
      super.viewDidLoad()
  }

  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
  }
}

上面应用程序的输出如下:

请注意,当我们按Call(呼叫)时,iOS会自动重新确认要拨打的号码。
iOS通过在切换应用程序之前征求用户的许可来增强UX。