Skip to content

Instantly share code, notes, and snippets.

@mattgallagher
Last active July 12, 2017 00:26
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/9df278f2c62833da82336f713bea6e31 to your computer and use it in GitHub Desktop.
Save mattgallagher/9df278f2c62833da82336f713bea6e31 to your computer and use it in GitHub Desktop.
public extension UIView {
// Return nearest common ancestor between two views
public func nearestCommonAncestor(with otherView: UIView) -> UIView? {
var mySuperviews = sequence(first: self, next: { $0.superview }).reversed().makeIterator()
var theirSuperviews = sequence(first: otherView, next: { $0.superview }).reversed().makeIterator()
var nca: UIView? = nil
while let mine = mySuperviews.next(), let theirs = theirSuperviews.next(), mine === theirs {
nca = mine
}
return nca
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment