Skip to content

Instantly share code, notes, and snippets.

@thejohnlima
Created March 5, 2022 20:47
Show Gist options
  • Save thejohnlima/b3bcef85c48e2302901a7578978b0797 to your computer and use it in GitHub Desktop.
Save thejohnlima/b3bcef85c48e2302901a7578978b0797 to your computer and use it in GitHub Desktop.
Extensions to help on UIAlertController implementation
import UIKit
extension UIAlertController {
struct Settings {
var title: String?
var message: String?
var style: UIAlertController.Style = .alert
var interfaceStyle: UIUserInterfaceStyle?
var actions: [Action] = [Action()]
var target: UIViewController?
struct Action {
var title: String? = "OK"
var style: UIAlertAction.Style = .default
var completion: ((UIAlertAction) -> Void)?
}
}
/// Present alert controller
/// - Parameters:
/// - settings: Alert settings
/// - animated: Present animated or not
/// - completion: Completion handler
static func present(_ settings: Settings, animated: Bool = true, completion: (() -> Void)? = nil) {
let controller = UIAlertController(title: settings.title, message: settings.message, preferredStyle: settings.style)
controller.overrideUserInterfaceStyle = settings.interfaceStyle ?? .unspecified
for action in settings.actions {
let alertAction = UIAlertAction(title: action.title, style: action.style, handler: action.completion)
controller.addAction(alertAction)
}
DispatchQueue.main.async {
let target = settings.target
target?.present(controller, animated: animated, completion: completion)
}
}
}
let settings = UIAlertController.Settings(
title: "Card",
message: "Card Name",
target: self
)
UIAlertController.present(settings)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment