iOS警报– UIAlertController

2023-05-16

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:

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

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:

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

iOSAlertController iOS警报控制器

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS警报– UIAlertController 的相关文章

  • 使用 UIWebView 显示 PDF 不起作用

    因此 我意识到有关使用 UIWebView 在应用程序 在 iPad 上 中显示 PDF 存在很多问题 我已经审查了我能找到的所有内容 但似乎找不到任何满意的东西 我想做的事情非常基本 所以我真的不知道为什么它不起作用 我需要做的就是在 U
  • 旋转 GPUImageTiltShiftFilter - GPUImage

    我想要一个非水平 GPUImageTiltShiftFilter 旋转 我想将其旋转到任意旋转角度 我还希望过滤器速度快 可以通过带有 UIRotationGestureRecongizer 的 UI 进行旋转 我该怎么做呢 啊 想通了 不
  • iOS Twitter NSURLErrorDomain 代码=-1012

    我正在尝试通过在我的应用程序中注册 Twitter 来获取用户的联系方式 我发现this https github com malcommac DMTwitterOAuthgithub上的项目看起来非常好 我只遇到一个问题 如果我使用来自
  • 在 Swift 中,如何为具有自动布局的 UIView 制作动画,就像页面滑入一样?

    我尝试创建一个 UIView 来表示一个大小与设备屏幕相同的页面 由于该应用程序支持方向 因此我使用 AutoLayout 来构建它 它工作正常 直到我尝试将页面动画化以从右侧滑入 经过一番研究后 我能想到的最好的办法是 myView UI
  • 如何将NSTextView的格式化内容转换为字符串

    我需要将 NSTextView 的内容从 Mac 应用程序传输到 iOS 应用程序 我使用 XML 作为传输文件格式 所以我需要将 NSTextView 的内容 文本 字体 颜色等 保存为字符串 有什么办法可以做到这一点吗 一种方法是存档
  • AGVTool new-version 和 What-version 不对应

    当我做 agvtool new version all 99 它更新我的 Info plist 文件 但是 如果我这样做 agvtool what version or agvtool next version 我收到此错误 There d
  • 如何在没有 MFMessageComposeViewController 的情况下发送和接收短信?

    我想发送和接收短信而不显示MFMessageViewController从我的申请中 有人能告诉我这怎么可能吗 不可能 除非您使用第 3 方 api 发送 接收短信
  • iOS 11 中的密码自动填充快速输入栏

    iOS 11 中引入了一项新功能 应用程序密码自动填充 此功能允许用户直接从键盘快速输入栏使用其应用程序中保存的密码 https techcrunch com 2017 06 08 ios 11s new password autofill
  • iOS 11 特定设置部分的 URL 方案停止工作

    我的应用程序使用 URL 方案将用户直接带到 设置 常规 关于 部分 以下 URL 在 10 3 x 中工作正常 应用程序首选项 根 常规 路径 关于 然而 这个 URL 方案在 iOS 11 GM 版本中不再有效 它仅启动 设置 应用程序
  • Xamarin.Forms 实现 AndHud 和 BTProgressHud

    谁能向我指出一个 Xamarin forms 示例 该示例在 Android 上使用 AndHud 在 iOS 上使用 BTProgressHud 或类似的东西 我知道这里有 ACR Xamarin Forms 示例https github
  • Swift UIImage 转换为 PDF

    在我的应用程序中 必须从 iPad Gallery 出售 UIImage 并将其转换为 PDF 并保存在服务器端 我可以选择图像并将其发送到服务器端 但后端说 pdf 为空 空数据 我还在控制台中看到警告 错误 发现扩展时遇到 发现 错误
  • React Native 模块中的 EADemo 永远不会收到委托方法handleEvent NSStreamEventOpenCompleted?

    我希望我有一个反应本机桥接模块 https facebook github io react native docs native modules ios html 线程 委托或生命周期问题 我不明白这些问题正在阻止接收委托方法调用 我需要
  • 比较两个 CGPoint 是否相等:对于输出相同点的两个对象返回不相等?

    根据这个问题 https stackoverflow com questions 26335052 how to compare cgpoints in swift 使用 和 应该可以让你检查两个之间是否相等CGPoint对象 然而 下面的
  • 两个滚动视图同时工作,一键触摸

    我正在其中开发应用程序 我必须一键同时处理两个滚动视图 这意味着如果我同时滚动一个滚动视图 另一个滚动视图必须随之滚动 如果这是可能的 那么如何才能做到呢 在包含两个滚动视图的视图控制器中实现 UIScrollViewDelegate 协议
  • 如何找到安全区域的高度和宽度?

    我正在尝试以编程方式为某些标签 按钮和文本字段设置相对于安全区域的高度和宽度的约束 例如 我希望将标签到安全区域顶部的距离设置为安全区域高度的 10 如何检索安全区域的高度和宽度 这是一个合理的方法吗 我的想法是 无论 iOS 设备如何 我
  • 电影播放完毕后关闭 AVPlayer

    我正在制作一个简单的 iPad 应用程序 按下按钮即可播放电影 电影播放 电影结束后我想关闭 AVPlayerView 以便它返回主屏幕 目前 当视频结束时 它停留在最后一帧 我现在的 ViewController Swift import
  • UIKeyboardFrameBeginUserInfoKey 和 UIKeyboardFrameEndUserInfoKey

    在管理键盘中文档 http developer apple com iphone library documentation StringsTextFonts Conceptual TextAndWebiPhoneOS KeyboardMa
  • 从 HealthKit 获取昨天的步数

    我正在构建一个供个人使用的应用程序 目前我正致力于如何从 healthkit 中准确获取昨天的步数 然后从那里将其放入变量中 我知道应该很容易 我有一个 HealthKitManager 类 它从视图内部调用该函数 然后将其附加到同一视图中
  • ipa 应用程序无法添加到我们的 itunes 库,它不是有效的应用程序

    我使用 xcode 6 和 swift 语言制作了一个未签名的 IPA 应用程序 我已压缩 app 文件并将其扩展名更改为 ipa 当我想在越狱的iPhone上安装这个 ipa文件时 出现以下错误 无法将应用程序 youtapp ipa 添
  • iOS 上有像 JUNG 这样的可视化框架吗?

    有没有类似的可视化框架JUNG http jung sourceforge net applet index html对于iOS 我想实现类似的东西this http prefuse org gallery graphview iOS 上最

随机推荐