封装uialertactionios

在iOS应用开发中,弹出式警告对话框是一种常见的用户界面元素,用于显示重要信息,提醒用户进行操作或者是提示特定操作成功。在本文中,我们将详细介绍如何封装一个使用UIAlertController和UIAlertAction的简单类库,以及它的使用方法。

一、概念与原理

UIAlertController是在iOS 8以后引入的一个类,用于取代旧版的UIAlertView类。它支持两种样式:alert和action sheet。在这篇文章中,我们将专注于使用UIAlertController创建基本的alert样式对话框。

UIAlertAction是UIAlertController中的一个重要元素,用于表示按钮和关联的操作。每个UIAlertAction都有一个标题、样式和关联的事件处理程序(可选)。

二、封装UIAlertActionIOS类库

下面是一个简单的UIAlertActionIOS类的实现代码:

```swift

import UIKit

class UIAlertActionIOS {

var title: String

var message: String

var preferredStyle: UIAlertController.Style

var actions: [UIAlertAction]

init(title: String, message: String, preferredStyle: UIAlertController.Style = .alert) {

self.title = title

self.message = message

self.preferredStyle = preferredStyle

self.actions = []

}

func addAction(title: String, style: UIAlertAction.Style = .default, handler: ((UIAlertAction) -> Void)? = nil) {

let action = UIAlertAction(title: title, style: style, handler: handler)

actions.append(action)

}

func present(in viewController: UIViewController) {

let alertController = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)

for action in actions {

alertController.addAction(action)

}

viewController.present(alertController, animated: true, completion: nil)

}

}

```

在这个简单的封装里,我们有以下几个主要组件:

1. 初始化(init)方法:用于设置对话框的标题、消息和类型(默认为.alert)。

2. addAction方法:用于添加UIAlertAction对象到对话框。可以设置按钮的标题、样式和关联的事件处理程序。

3. present方法:用于显示UIAlertController。传入UIViewController对象,通过该对象显示对话框。

三、使用封装好的UIAlertActionIOS类库

使用我们刚刚创建的UIAlertActionIOS类库是非常简单的。下面是一个在视图控制器中使用该类库的示例代码:

```swift

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

}

@IBAction func showAlertButtonTapped(_ sender: UIButton) {

let alertActionIOS = UIAlertActionIOS(title: "提示", message: "这是一个提示信息")

alertActionIOS.addAction(title: "取消", style: .cancel) { _ in

print("取消按钮被点击")

}

alertActionIOS.addAction(title: "确认", style: .default) { _ in

print("确认按钮被点击")

}

alertActionIOS.present(in: self)

}

}

```

执行流程如下:

1. 创建一个UIAlertActionIOS实例,设置标题和消息内容。

2. 调用addAction方法,为实例添加按钮及关联操作。

3. 调用present方法,将对话框显示在视图控制器中。

总结

通过上述简单的封装,我们可以轻松地创建和显示自定义的警告对话框。值得注意的是,此类仅适用于基本的警告对话框创建,如果需要实现更复杂的功能,您需要对UIAlertController进行进一步封装和扩展。此外,本文中的代码仅适用于iOS 8及更高版本。希望本文能够帮助您更好地理解UIAlertController和UIAlertAction在iOS开发中的应用。