Created
July 17, 2018 11:10
-
-
Save AshvinGudaliya/b08229fc99187e82e9c918d1a752f616 to your computer and use it in GitHub Desktop.
UITapGestureRecognizer directly in UIView extension
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
import UIKit | |
open class AGTapGestureClosure: UITapGestureRecognizer { | |
private var tapAction: ((UITapGestureRecognizer) -> Void)? | |
public override init(target: Any?, action: Selector?) { | |
super.init(target: target, action: action) | |
} | |
public convenience init ( | |
tapCount: Int = 1, | |
fingerCount: Int = 1, | |
action: ((UITapGestureRecognizer) -> Void)?) { | |
self.init() | |
self.numberOfTapsRequired = tapCount | |
self.numberOfTouchesRequired = fingerCount | |
self.tapAction = action | |
self.addTarget(self, action: #selector(didTap(_:))) | |
} | |
@objc open func didTap (_ tap: UITapGestureRecognizer) { | |
tapAction? (tap) | |
} | |
} | |
extension UIView { | |
@discardableResult | |
func tapped(callback: @escaping ((UITapGestureRecognizer) -> Void)) -> AGTapGestureClosure { | |
self.isUserInteractionEnabled = true | |
let tapped = AGTapGestureClosure(action: callback) | |
self.addGestureRecognizer(tapped) | |
return tapped | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment