Skip to content

Instantly share code, notes, and snippets.

@pardel
Created September 19, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pardel/abca3aa85f93ce8349ef to your computer and use it in GitHub Desktop.
Save pardel/abca3aa85f93ce8349ef to your computer and use it in GitHub Desktop.
UIAlerView with Swift closures
//
// AlertView.swift
//
import UIKit
// holding array so the AlertView objects don't go out of scope
internal var alerts = [AlertView]()
// simple structure to hold button name and its closure
struct AlertViewButton {
var title : String
var action: () -> Void
}
// the alert view class
class AlertView: NSObject, UIAlertViewDelegate {
var title : String!
var message: String!
var cancelButton : AlertViewButton!
var otherButtons = [AlertViewButton]()
init(title: String, message: String, cancelButtonTitle: String, cancelButtonAction: () -> Void) {
super.init()
self.title = title
self.message = message
self.cancelButton = AlertViewButton(title: cancelButtonTitle, action: cancelButtonAction)
}
func addButtonWithTitle(title: String, action: () -> Void) -> Void {
let button = AlertViewButton(title: title, action: action)
otherButtons.append(button)
}
func show() {
let alertView = UIAlertView(title: self.title, message: self.message, delegate: self, cancelButtonTitle: self.cancelButton.title)
for button in otherButtons {
alertView.addButtonWithTitle(button.title)
}
// add to holding array; otherwise the object is released & delegate method never gets called
alerts.append(self)
alertView.show()
}
// UIAlertViewDelegate
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 0 {
cancelButton.action()
return
}
if otherButtons.count <= buttonIndex {
let button = otherButtons[buttonIndex - 1]
button.action()
}
// remove from holding array
if let index = alerts.indexOf(self) {
alerts.removeAtIndex(index)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment