Last active
July 12, 2017 00:48
-
-
Save mattgallagher/ef4d63abdef87221b7ae8fb532e39fd8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { | |
public func nearestCommonAncestor(with otherView: UIView) -> UIView? { | |
let myHierarchyDepth = sequence(first: self, next: { $0.superview }).reduce(0) { (count, view) in count + 1 } | |
let otherHierarchyDepth = sequence(first: otherView, next: { $0.superview }).reduce(0) { (count, view) in count + 1 } | |
var longest = sequence(first: myHierarchyDepth < otherHierarchyDepth ? otherView : self, next: { $0.superview }) | |
var shortest = sequence(first: myHierarchyDepth < otherHierarchyDepth ? self : otherView, next: { $0.superview }) | |
return zip( | |
longest.dropFirst(abs(myHierarchyDepth - otherHierarchyDepth)), | |
shortest | |
).first(where: { $0.0 === $0.1 })?.0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment