Last active
August 29, 2015 14:17
-
-
Save kwylez/14ab05683989b4cd56d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UIViewExtensions.swift | |
// Singles | |
// | |
// Created by Cory D. Wiles on 2/19/15. | |
// Copyright (c) 2015 Cory WIles. All rights reserved. | |
// | |
import UIKit | |
/// Need to subclass NSObject or you get nasty crash (methodSignatureForSelector) | |
private class ClosureWrapper: NSObject, NSCopying { | |
var closure: (() -> Void)? | |
convenience init(closure: (() -> Void)?) { | |
self.init() | |
self.closure = closure? | |
} | |
func copyWithZone(zone: NSZone) -> AnyObject { | |
var wrapper: ClosureWrapper = ClosureWrapper() | |
wrapper.closure = closure? | |
return wrapper | |
} | |
} | |
extension UIView { | |
private struct AssociatedKeys { | |
static var SNGLSActionHandlerTapBlockKey = "sngls_ActionHandlerTapBlockKey" | |
static var SNGLSActionHandlerTapGestureKey = "sngls_ActionHandlerTapGestureKey" | |
} | |
var tapAction: (() -> Void)? { | |
get { | |
if let cl = objc_getAssociatedObject(self, &AssociatedKeys.SNGLSActionHandlerTapBlockKey) as? ClosureWrapper { | |
return cl.closure | |
} | |
return nil | |
} | |
set { | |
objc_setAssociatedObject( | |
self, | |
&AssociatedKeys.SNGLSActionHandlerTapBlockKey, | |
ClosureWrapper(newValue), | |
UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
) | |
} | |
} | |
var tapGesture: UITapGestureRecognizer? { | |
get { | |
if let gesture: UITapGestureRecognizer = objc_getAssociatedObject(self, &AssociatedKeys.SNGLSActionHandlerTapGestureKey) as? UITapGestureRecognizer { | |
return gesture | |
} | |
return nil | |
} | |
set { | |
objc_setAssociatedObject(self, &AssociatedKeys.SNGLSActionHandlerTapGestureKey, (newValue), UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) | |
} | |
} | |
func sngls_setTapAction(completionBlock:() -> Void) { | |
self.tapAction = completionBlock | |
self.tapGesture = UITapGestureRecognizer(target: self, action: Selector("sngls__handleActionForTapGesture:")) | |
self.addGestureRecognizer(self.tapGesture!) | |
} | |
// MARK: Semi Private Methods | |
func sngls__handleActionForTapGesture(gesture: UITapGestureRecognizer) -> Void { | |
if (gesture.state == UIGestureRecognizerState.Ended) { | |
if let action: ClosureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.SNGLSActionHandlerTapBlockKey) as? ClosureWrapper { | |
action.closure!() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment