Skip to content

Instantly share code, notes, and snippets.

@shaps80
Created December 13, 2019 17:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaps80/d73b75e8ffa192bdf1a2ca08a510d015 to your computer and use it in GitHub Desktop.
Save shaps80/d73b75e8ffa192bdf1a2ca08a510d015 to your computer and use it in GitHub Desktop.
A UIView helper extension that finds the 'key' view in the controller's hierarchy. Useful for finding a UITableView/UICollectionView or any other view that's NOT the controller's root view.
import UIKit
internal extension UIViewController {
/// Returns the 'key' view for this controller. I.e. the top-most visible view that covers the view's entire bounds.
/// This is generally the controller's root view, but it could also be a nested table/collection view, etc...
@objc var _keyView: UIView {
return view._keyViews(in: self).last ?? view
}
}
internal extension UIView {
/// Returns all potentional 'key' views in this controller
/// - Parameter controller: The controller to search
@objc func _keyViews(in controller: UIViewController) -> [UIView] {
let views = subviews.filter { $0._isKeyView(in: controller) }
return views + views.flatMap { $0._keyViews(in: controller) }
}
/// Returns true if this view is a 'key' in the specified controller
/// - Parameter controller: The controller to search
@objc func _isKeyView(in controller: UIViewController) -> Bool {
return alpha > 0
&& !isHidden
&& isUserInteractionEnabled
&& (frame.size == controller.view.safeAreaLayoutGuide.layoutFrame.size
|| frame.size == controller.view.bounds.size)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment