iOS警报– UIAlertController

In this tutorial, we’ll be discussing the UIAlertController class and how it is handy to create different types of Alerts in our iOS Application.

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

iOS警报– UIAlertController (iOS Alert – UIAlertController)

UIAlertController is used to configure alerts and actionsheets with various actions to choose from.

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

We have already ActionSheets in another tutorial. Here we’ll be focussing on the alerts style of UIAlertController.

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

Along with the actions, we can also add an image logo. We can set textfield inputs in the Alerts as well that we shall see shortly.

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

UIAlertController is often used to ask the user to open a type of application. Example: Call/Message. Camera/Gallery.

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

Choose among the different Map apps.

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

默认警报 (Default Alerts)

A basic UIAlertController Alert dialog can be created in the following way in Swift.

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

let alertController = UIAlertController(title: "JournalDev.com", 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)

A title, message, and the preferred style are passed. Every Button in the UIAlertController is a UIAlertAction.

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

The UIAlertAction buttons are of three styles: default, destructive, cancel. The destructive style is in color red.

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

动作按钮 (Action Buttons)

Every UIALertAction has a handler argument wherein we add our logic of the action to be performed.

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

let alertController = UIAlertController(title: "JournalDev", 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)

In the above code, we have added log statements in the Swift closures. You can pass your own custom functions here as well.

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

UIAlertController带调用,消息,打开地图 (UIAlertController With Call, Messsage, Open Maps)

In the following code, each of our action buttons will be used for calling, messaging, opening a third party application from the Alert Dialog.

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

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)

The url schema to pass the phone number is: “tel:/\(phone_number_pass_here)”
For opening a third party application such as Apple Maps, we need to use it’s pre-defined custom schema.

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

To open Google Maps Application we first need to check if the application is installed or not:

要打开Goog​​le 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 (Add Image Logo And Launch a URL)

We can add an image logo to each of the action buttons.

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

Also, we can set an action that launches the URL in the default web browser of our iOS Device.

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

let alertController = UIAlertController(title: "JournalDev.com", message: "Alert Dialog with Image", preferredStyle: .alert)
        
        
        let imageAction = UIAlertAction(title: "Website", style: .default, handler: {
            (action) in
            UIApplication.shared.open(URL(string: "https://www.journaldev.com")!, 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)

For each action, we can set the image filename defined in our Assets folder of the XCode project.

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

To set the same color for each of the action buttons do the following:

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

alertController.view.tintColor = UIColor.orange

添加一个TextField (Adding a 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)

Inside the addTextField function, we can configure the TextField. All of the TextFields would be stacked vertically.

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

Let’s merge all of these in our XCode iOS Application.

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

主机板 (MainStoryboard)

We have connected each of the Buttons to the ViewController.swift and created an IBAction function for each of them.

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

In the Assets folder import a png image file. Make sure the key name is the same as the one you set in the ViewController.swift below:

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

import UIKit

class ViewController: UIViewController {

    @IBAction func showAlert(_ sender: Any) {
        
        let alertController = UIAlertController(title: "JournalDev.com", 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: "JournalDev", 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: "JournalDev.com", 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.journaldev.com")!, 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()
    }
}

The output of the above application in action is given below:

ios alert UIAlertController

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

Notice that when we press Call, iOS automatically re-confirms the number to be dialed. iOS does this to enhance the UX by asking for the user’s permission before switching the application.

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

This brings an end to this tutorial. You can download the project from the link below:

本教程到此结束。 您可以从下面的链接下载项目:

翻译自: https://www.journaldev.com/22028/ios-alert-uialertcontroller

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值