Skip to content

Instantly share code, notes, and snippets.

@ryancumley
Created December 19, 2014 19:00
Show Gist options
  • Save ryancumley/d376c680e89a7a145a59 to your computer and use it in GitHub Desktop.
Save ryancumley/d376c680e89a7a145a59 to your computer and use it in GitHub Desktop.
Class in closure delegate pattern for UIAlertView
/*
Idea for this comes from https://gist.github.com/austinzheng/8fda3f61e1fd06383928#file-main-swift-L19
In an iOS 7.x supporting app which can't use UIAlertController, rather than fork execution paths based on iOS version, we could wire up an old fashioned UIAlertView this way. Still feels more 'block' based and clean to handle, since all the UIAlertViewDelegate stuff is contained within the 'nested-class-in-closure'.
*/
class SampleViewController: UIViewController {
var askTheUserSomethingAlert: UIAlertView
var strongAlertDelegate: UIAlertViewDelegate?
required init(coder aDecoder: NSCoder) {
askTheUserSomethingAlert = UIAlertView()
super.init()
setup()
}
func setup() {
strongAlertDelegate = {
[weak self] in
class AnonymousAlertDelegate: NSObject, UIAlertViewDelegate {
var parent: SampleViewController?
private func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
parent?.handleAlertViewButtonTap(forIndex: buttonIndex)
}
}
let anonymousDelegate = AnonymousAlertDelegate()
anonymousDelegate.parent = self
return anonymousDelegate
}()
askTheUserSomethingAlert.delegate = strongAlertDelegate
}
func handleAlertViewButtonTap(forIndex index: Int) {
//do things here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment