Skip to content

Instantly share code, notes, and snippets.

@mattgallagher
Last active July 12, 2017 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattgallagher/ef4d63abdef87221b7ae8fb532e39fd8 to your computer and use it in GitHub Desktop.
Save mattgallagher/ef4d63abdef87221b7ae8fb532e39fd8 to your computer and use it in GitHub Desktop.
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