Skip to content
This repository has been archived by the owner on Nov 2, 2019. It is now read-only.

Commit

Permalink
Improve UIAlertController APIs in the SwiftCatalog sample app (#92)
Browse files Browse the repository at this point in the history
  • Loading branch information
mohshin-shah authored and nlutsenko committed Nov 7, 2016
1 parent 52b4f27 commit 1e99f6a
Showing 1 changed file with 79 additions and 6 deletions.
85 changes: 79 additions & 6 deletions Samples/Catalog/Sources/AlertController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,85 @@
import Foundation
import UIKit

extension UIAlertAction {
/// Action types most commonly used
public enum ActionType {
///Ok Option
case ok
/// Default Cancel Option
case cancel
/// Destructive action with custom title
case destructive(String)
/// Custom action with title and style
case custom(String, UIAlertActionStyle)

/**
Creates the action instance for UIAlertController
- parameter handler: Call Back function
- returns UIAlertAction Instance
*/
public func action(handler: ((String) -> Void)? = nil) -> UIAlertAction {
//Default value
var actionStyle = UIAlertActionStyle.default
var title = ""
// Action configuration based on the action type
switch self {

case .cancel:
actionStyle = .cancel
title = "Cancel"

case .destructive(let optionTitle):
title = optionTitle
actionStyle = .destructive

case .custom(let optionTitle, let style):
title = optionTitle
actionStyle = style

default:
title = "OK"
}
//Creating UIAlertAction instance
return UIAlertAction(title:title, style:actionStyle) { nativeAction in
if let handler = handler {
handler(title)
}
}

}
}
}

extension UIAlertController {
convenience init(title: String, message: String) {
self.init(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: NSLocalizedString("OK", comment: "OK action"),
style: .default,
handler: nil)
addAction(action)
/**
Creates the alert view controller using the actions specified
- parameter title: Title of the alert.
- parameter message: Alert message body.
- parameter actions: Variable numbre of actions as an Array of actionType values.
- parameter style: UIAlertControllerStyle enum value
- parameter handler: Handler block/closure for the clicked option.
*/
convenience init(title: String,
message: String,
actions: UIAlertAction.ActionType?...,
style: UIAlertControllerStyle = .alert,
handler: ((String) -> Swift.Void)? = nil) {

//initialize the contoller (self) instance
self.init(title: title, message: message, preferredStyle: style)

if actions.isEmpty {
addAction(UIAlertAction.ActionType.ok.action(handler: handler))
} else {
//Fetching actions specidied by the user and adding actions accordingly
for actionType in actions {
addAction((actionType?.action(handler: handler))!)
}
}

}
}

0 comments on commit 1e99f6a

Please sign in to comment.