Created
June 12, 2018 12:29
-
-
Save EfraimB/3ccd259afa58b365525a6cfaa05809e5 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
public extension UIView { | |
private struct ExtendedTouchAssociatedKey { | |
static var outsideOfBounds = "viewExtensionAllowTouchesOutsideOfBounds" | |
} | |
/// This propery is set on the parent of the view that first clips the content you want to be touchable | |
/// outside of the bounds | |
var allowTouchesOfViewsOutsideBounds:Bool { | |
get { | |
return objc_getAssociatedObject(self, &ExtendedTouchAssociatedKey.outsideOfBounds) as? Bool ?? false | |
} | |
set { | |
UIView.swizzlePointInsideIfNeeded() | |
subviews.forEach({$0.allowTouchesOfViewsOutsideBounds = newValue}) | |
objc_setAssociatedObject(self, &ExtendedTouchAssociatedKey.outsideOfBounds, newValue, .OBJC_ASSOCIATION_RETAIN) | |
} | |
} | |
func hasSubview(at point:CGPoint) -> Bool { | |
if subviews.count == 0 { | |
return self.bounds.contains(point) | |
} | |
return subviews.contains(where: { (subview) -> Bool in | |
let converted = self.convert(point, to: subview) | |
return subview.hasSubview(at: converted) | |
}) | |
} | |
static private var swizzledMethods:Bool = false | |
@objc func _point(inside point: CGPoint, with event: UIEvent?) -> Bool { | |
if allowTouchesOfViewsOutsideBounds { | |
return _point(inside:point,with:event) || hasSubview(at: point) | |
} | |
return _point(inside:point,with:event) | |
} | |
static private func swizzlePointInsideIfNeeded() { | |
if swizzledMethods { | |
return | |
} | |
swizzledMethods = true | |
let aClass: AnyClass! = UIView.self | |
let originalSelector = #selector(point(inside:with:)) | |
let swizzledSelector = #selector(_point(inside:with:)) | |
swizzle(forClass: aClass, originalSelector: originalSelector, swizzledSelector: swizzledSelector) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment